Java service which extracts the value of a field at runtime - java

I need to build a java service which extracts the value of a field at runtime. The path of the field in the canonical and the canonical document itself should be given as input.
Eg:
fromDoc consists of sub documents within it, in a hierarchy, ie.
fromDoc/Data/Parameters/outDate
•fromDoc
•Data
•Parameters
•outDate(string)
For inStringValues I give the input as 'fromDoc/Data/Parameters/outDate'
the output should return the value of the variable 'fromDoc/Data/Parameters/outDate' at run time.
I have a code which implements this with the key value pair logic.
IDataCursor pipelineCursor = pipeline.getCursor();
// fromDoc
IData fromDoc = IDataUtil.getIData( pipelineCursor, "fromDoc" );
String[] inStringValues = IDataUtil.getStringArray( pipelineCursor, "inStringValues" );
if ( fromDoc == null)
{
return;
}
pipelineCursor.destroy();
int len = inStringValues.length;
String[] outStrings = new String[len];
IDataCursor fromCursor = fromDoc.getCursor();
boolean hasData = false;
while( fromCursor.next() )
{
for(int i=0;i<len;i++)
{
String key = fromCursor.getKey();
String val = fromCursor.getValue().toString();
if(key.equals(inStringValues[i]))
{
outStrings[i]=key + "," + val;
}
}
}
fromCursor.destroy();
IDataCursor pipelineCursor_1 = pipeline.getCursor();
IDataUtil.put( pipelineCursor_1, "outStrings", outStrings );
pipelineCursor_1.destroy();
Please let me know how I can modify this code to implement the above mentioned logic?
Or let me know if anyone has such an existing service with you.

Tundra has a service that does exactly what you need: tundra.document:get($document, $key).
$document is the com.wm.data.IData document you want to extract the value from
$key is the name of the key you want to extract, and can be fully-qualified and include array indexing, for example "path/to/my[1]/key"
The relevant Java code is as follows:
public static final void get(IData pipeline) throws ServiceException {
IDataCursor cursor = pipeline.getCursor();
try {
IData document = IDataUtil.getIData(cursor, "$document");
String key = IDataUtil.getString(cursor, "$key");
IDataUtil.put(cursor, "$value", get(document, key));
} finally {
cursor.destroy();
}
}
// wrapper class for fully qualified IData keys
public static class Key {
public static final String SEPARATOR = "/";
public static final java.util.regex.Pattern INDEX_PATTERN = java.util.regex.Pattern.compile("\\[(-?\\d+?)\\]$");
protected boolean hasIndex = false;
protected int index = 0;
protected String key = null;
public Key(String key) {
java.util.regex.Matcher matcher = INDEX_PATTERN.matcher(key);
StringBuffer buffer = new StringBuffer();
while(matcher.find()) {
hasIndex = true;
index = Integer.parseInt(matcher.group(1));
matcher.appendReplacement(buffer, "");
}
matcher.appendTail(buffer);
this.key = buffer.toString();
}
public boolean hasIndex() {
return hasIndex;
}
public int getIndex() {
return index;
}
public String toString() {
return key;
}
public static java.util.Queue<Key> parse(String key) {
String[] parts = key.split(SEPARATOR);
java.util.Queue<Key> queue = new java.util.ArrayDeque<Key>(parts.length);
for (int i = 0; i < parts.length; i++) {
queue.add(new Key(parts[i]));
}
return queue;
}
public static boolean isFullyQualified(String key) {
return key != null && (key.contains(SEPARATOR) || INDEX_PATTERN.matcher(key).find());
}
}
// returns the value associated with the given key from the given IData document
public static Object get(IData input, String key) {
Object value = null;
if (input != null && key != null) {
// try finding a value that matches the literal key
IDataCursor cursor = input.getCursor();
try {
value = IDataUtil.get(cursor, key);
} finally {
cursor.destroy();
}
// if value wasn't found using the literal key, the key could be fully qualified
if (value == null && Key.isFullyQualified(key)) value = get(input, Key.parse(key));
}
return value;
}
// gets a value from an IData document with a fully qualified key
protected static Object get(IData input, java.util.Queue<Key> keys) {
Object value = null;
if (input != null && keys != null && keys.size() > 0) {
IDataCursor cursor = input.getCursor();
Key key = keys.remove();
if (keys.size() > 0) {
if (key.hasIndex()) {
IData[] array = IDataUtil.getIDataArray(cursor, key.toString());
value = get(get(array, key.getIndex()), keys);
} else {
value = get(IDataUtil.getIData(cursor, key.toString()), keys);
}
} else {
if (key.hasIndex()) {
Object[] array = IDataUtil.getObjectArray(cursor, key.toString());
value = get(array, key.getIndex());
} else {
value = IDataUtil.get(cursor, key.toString());
}
}
cursor.destroy();
}
return value;
}
public static <T> T get(T[] array, int index) {
T item = null;
if (array != null) {
// support reverse/tail indexing
if (index < 0) index += array.length;
item = array[index];
}
return item;
}
Note: Tundra has a complementary service for setting a value in a com.wm.data.IData document too: tundra.document.put($document, $key, $value).

What about this ?
// fromDoc
IDataCursor cursor = pipeline.getCursor();
IData fromDoc = IDataUtil.getIData(cursor, "fromDoc");
if (fromDoc == null) {
return;
}
// Data
cursor = fromDoc.getCursor();
IData Data = IDataUtil.getIData(cursor, "Data");
if (Data == null) {
return;
}
// Parameters
cursor = Data.getCursor();
IData Parameters = IDataUtil.getIData(cursor, "Parameters");
if (Parameters == null) {
return;
}
// outDate
cursor = Parameters.getCursor();
String outDate = IDataUtil.getString(cursor, "outDate");
// Here I have the outDate value

Related

Huffman algorithm, building code tree dart null-safety java reference

So here is my dart version of java's huffman algorithm. I have a problem with getCodeForChar function, it says what return type of String can't be null, and even if for every return i added +'h'. How to deal with null-safety at that case?
Originally the function is:
public String getCodeForCharacter(Character ch, String parentPath) {
if (content == ch) {
return parentPath;
} else {
if (left != null) {
String path = left.getCodeForCharacter(ch, parentPath + 0);
if (path != null) {
return path;
}
}
if (right != null) {
String path = right.getCodeForCharacter(ch, parentPath + 1);
if (path != null) {
return path;
}
}
}
return null;
}
And my full code:
import 'dart:collection';
void main() {
String text = 'where there,s a will there,s a way';
SplayTreeMap? frequencies = countFrequency(text);
frequencies.forEach((key, value) {
print('$key \t $value');
});
var sk = frequencies.values.toList();
print(sk);
List<CodeTreeNode> codeTreeNode = [];
for (String? c in frequencies.keys) {
codeTreeNode.add(new CodeTreeNode.simple(c, frequencies[c]));
}
CodeTreeNode tree = huffman(codeTreeNode);
SplayTreeMap<String, String> codes = SplayTreeMap();
for (String c in frequencies.keys) {
//codes.addAll(c, (value) => tree.getCodeForChar(c, ""));
codes.addAll({c: tree.getCodeForChar(c, "")});
}
codes.forEach((key, value) {
print('$key \t $value');
});
}
SplayTreeMap countFrequency(String text) {
SplayTreeMap? myMap = SplayTreeMap<String, int>();
int tempCount = 0;
// for (int i = 0; i < text.length; i++) {
// String c = text[i];
// int count = myMap[];
// //myMap[int count]
// myMap[c] = count != -1 ? count + 1 : 1;
// }
for (int i = 0; i < text.length; i++) {
String c = text[i];
if (myMap.containsKey(c)) {
//tempCount++;
//myMap[text[i]] = tempCount;
tempCount = myMap[c] + 1;
myMap.update(c, (value) => tempCount);
} else {
myMap[c] = 1;
}
//счетчик = мапа[i] +1;
//заменить эту валью на счетчик
}
return myMap;
}
CodeTreeNode huffman(List<CodeTreeNode> codeTreeNodes) {
while (codeTreeNodes.length > 1) {
codeTreeNodes.sort();
CodeTreeNode left = codeTreeNodes.removeAt(codeTreeNodes.length - 1);
CodeTreeNode right = codeTreeNodes.removeAt(codeTreeNodes.length - 1);
CodeTreeNode parent =
CodeTreeNode.hard(null, right.weight + left.weight, left, right);
codeTreeNodes.add(parent);
}
return codeTreeNodes[0];
}
class CodeTreeNode implements Comparable<CodeTreeNode> {
String? content;
//List<Node> children = [];
int weight;
CodeTreeNode? left;
CodeTreeNode? right;
CodeTreeNode.simple(this.content, this.weight);
CodeTreeNode.hard(this.content, this.weight, this.left, this.right);
// Node(String content, int weight){(this.content, this.weight)
// }
#override
int compareTo(CodeTreeNode other) {
// TODO: implement compareTo
//throw UnimplementedError();
return other.weight - weight;
}
String getCodeForChar(String ch, String parentPath) {
if (content == ch) {
return 'h'+ parentPath;
} else {
if (left != null) {
String path = left.getCodeForChar(ch, parentPath + '0');
if (path != null) {
return 'h'+path;
}
}
if (right != null) {
String path = right.getCodeForChar(ch, parentPath + '1');
if (path != null) {
return 'h'+ path;
}
}
}
return 'hui';
}
}
Inserting you code int DartPad shows two errors.
The method 'getCodeForChar' can't be unconditionally invoked because the receiver can be 'null'.
Fixing this is easy: Insert the bang operator ('!'):
String path = left!.getCodeForChar(ch, parentPath + '0');
See also Working with nullable fields

Writing simple String hashMap using parallel arrays. Getting null value for some keys after rehashing

The first time I get the collision in put method ie when hasKey returns -1 the rehashing method starts and value that triggered collision goes to doubled array to likely empty slot. But System.out.println(m.get("1000")); gives me null for some keys which means they were lost. I don't understand how they could be lost because there is nothing to override them in keyArray.
import java.util.*;
public class StringMapParallel implements Iterable<String>{
private int nButckets = 2000;
private String[] keyArray = new String[nButckets];
private String[] valueArray = new String[nButckets];
private int numberOfEntries = 0;
public static void main(String[] args) {
StringMapParallel m = new StringMapParallel();
;
for (int i = 0; i < 8000; i++) {
m.put(String.valueOf(i), String.valueOf(i));
}
System.out.println(m.get("1000"));
}
private void rehashing() {
if (numberOfEntries > (int) (0.3 * nButckets)) {
int newBucketsNumber = nButckets * 2;
String[] newKeyArray = new String[newBucketsNumber];
String[] newValueArray = new String[newBucketsNumber];
for (int i = 0; i < keyArray.length; i++) {
if (keyArray[i] != null) {
int index = keyArray[i].hashCode() % newBucketsNumber;
newKeyArray[index] = keyArray[i];
newValueArray[index] = valueArray[keyArray[i].hashCode() % nButckets];
}
}
/*
for (String key: this) {
int index = key.hashCode() % newBucketsNumber;
newKeyArray[index] = key;
if (key == null) System.out.println(key);
newValueArray[index] = valueArray[key.hashCode() % nButckets];
}
*/
keyArray = newKeyArray;
valueArray = newValueArray;
nButckets = newBucketsNumber;
}
}
public void put(String key, String value) {
int index = key.hashCode() % nButckets;
int hasKey = hasKey(index, key);
if (hasKey == 1) {
valueArray[index] = value;
} else if (hasKey == 0){
keyArray[index] = key;
valueArray[index] = value;
numberOfEntries++;
} else {
rehashing();
index = key.hashCode() % nButckets;
keyArray[index] = key;
valueArray[index] = value;
numberOfEntries++;
}
}
public String get(String key) {
int index = key.hashCode() % nButckets;
if (hasKey(index, key) == 1) return valueArray[index];
return null;
}
private int hasKey(int index, String key) {
if (keyArray[index] == null) {
return 0;
} else if (keyArray[index].equals(key)) {
return 1;
} else {
return -1;
}
}
public Iterator<String> iterator(){
Iterator<String> iter = new Iterator<String>() {
private int currentIndex = 0;
private int nEntries = 0;
#Override
public boolean hasNext() {
return nEntries < numberOfEntries && numberOfEntries != 0;
}
#Override
public String next() {
for (int i = currentIndex; i < keyArray.length; i++) {
if (keyArray[i] != null) {
currentIndex = i + 1;
nEntries++;
return keyArray[i];
}
}
return null;
}
};
return iter;
}
}
The value of int index = key.hashCode() % nButckets; in your algorithm for key 1000 and 6357 is same, which is 1423. Hence, the your algorithm overwrites keyArray[1423]=1000 with keyArray[1423]=6357
When you are printing m.get(String.valueOf(1000)), following get() method checks for index as well as key, hence it would return null. Read comment in the code for further explanation.
public String get(String key) {
//System.out.println(key+" "+ key.hashCode());
int index = key.hashCode() % nButckets;
System.out.println(index+"bfb"+hasKey(index, key));
//hasKey(index, key) would return -1, because key[1423] is 6357, and not 1000 as you expected.
if (hasKey(index, key) == 1) return valueArray[index];
return null;
}
private int hasKey(int index, String key) {
//System.out.println(keyArray[index]);
if (keyArray[index] == null) {
return 0;
} else if (keyArray[index].equals(key)) {
return 1;
} else {
return -1;
}
}

Java not saving all data

I have a program that saves/loads data to a text file. However, some data seems to not be saving, and I can't figure out why.
Here's a simplified version of the code.
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
public class Test {
private static DumperOptions options;
private static File saveLocation;
private static Map<String, Object> data;
private static Representer representer;
private static String path;
private static Yaml yaml;
private static void setup() {
saveLocation = new File(path);
if (!saveLocation.exists())
try {
saveLocation.createNewFile();
} catch (IOException exception) {
exception.printStackTrace();
}
setupDumper();
yaml = new Yaml(representer, options);
data = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
}
private static void setupDumper() {
options = new DumperOptions();
representer = new Representer();
options.setIndent(2);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setAllowUnicode(Charset.defaultCharset().name().contains("UTF"));
representer.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
}
public static boolean contains(String key) {
return data.containsKey(key);
}
public static boolean exists() {
return data != null;
}
public static boolean hasValue(String key) {
Object tempObject = data.get(key);
return (tempObject != null);
}
public static boolean isEmpty() {
return data.isEmpty() || data == null;
}
public static int getInteger(String key) {
Object tempObject = get(key);
if (tempObject instanceof Integer)
return (Integer) tempObject;
if (tempObject instanceof String)
return Integer.parseInt(tempObject.toString());
if (tempObject instanceof Number)
return Integer.parseInt(tempObject.toString());
return -1;
}
public static Object get(String key) {
if (isEmpty())
return null;
if (key.contains(".")) {
String[] nodes = key.split("\\.");
Map<String, Object> currParent;
if (data.containsKey(nodes[0]) && (data.get(nodes[0]) instanceof Map))
currParent = (Map) data.get(nodes[0]);
else return null;
if (nodes.length > 1) {
for (int i = 1; i < nodes.length - 1; i++) {
if (currParent.containsKey(nodes[i]) && (currParent.get(nodes[i]) instanceof Map))
currParent = (Map) currParent.get(nodes[i]);
else return null;
}
if (currParent.containsKey(nodes[nodes.length - 1]))
return currParent.get(nodes[nodes.length - 1]);
}
} else if (!contains(key) || (contains(key) && !hasValue(key)))
return null;
return data.get(key);
}
public static FileReader read(File file) {
try {
if (!file.exists())
return null;
return new FileReader(file);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
}
return null;
}
public static boolean load() {
setup();
FileReader reader = read(saveLocation);
if (reader == null) {
data = Collections.synchronizedMap(new LinkedHashMap<String, Object>());
return true;
}
data = Collections.synchronizedMap((Map<String, Object>) yaml.load(reader));
System.out.println(getInteger("Settings.Difficulty.Level"));
System.out.println(getInteger("Settings.Difficulty.Locked"));
System.out.println(getInteger("Settings.Cheats.Enabled"));
System.out.println(getInteger("Settings.Cheats.Locked"));
System.out.println(getInteger("Settings.GUI.Enabled"));
System.out.println(data.toString());
return true;
}
public static void save() {
//Settings
set("Settings.Difficulty.Level", 1);// not saving
set("Settings.Difficulty.Locked", 2);
set("Settings.Cheats.Enabled", 3); // not saving
set("Settings.Cheats.Locked", 4);
set("Settings.GUI.Enabled", 5);
try {
if (!saveLocation.exists())
saveLocation.createNewFile();
FileWriter writer = new FileWriter(saveLocation);
writer.write(yaml.dump(data));
writer.flush();
writer.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
public static void set(String key, Object object) {
if (!exists())
return;
if (key.contains(".")) {
String[] nodes = key.split("\\.");
// if data doesn't contain top-level node, create nested Maps
if (!data.containsKey(nodes[0])) {
Map<String, Object> currNode = new HashMap<>(), prevNode;
currNode.put(nodes[nodes.length - 1], object);
for (int i = nodes.length - 2; i > 0; i--) {
prevNode = currNode;
currNode = new HashMap<>();
currNode.put(nodes[i], prevNode);
}
// set top-level node to previous parent
data.put(nodes[0], currNode);
} else { // if data contains top-level node, work through each Map
Map[] prevNodes = new LinkedHashMap[nodes.length - 1];
if (nodes.length > 1) {
for (int i = 0; i <= nodes.length - 2; i++) {
if (data.containsKey(nodes[i]) && (data.get(nodes[i]) instanceof Map))
prevNodes[i] = new LinkedHashMap((Map) data.get(nodes[i]));
else if (!data.containsKey(nodes[i]))
prevNodes[i] = new LinkedHashMap();
}
prevNodes[prevNodes.length - 1].put(nodes[nodes.length - 1], object);
for (int i = prevNodes.length - 1; i >= 1; i--)
prevNodes[i - 1].put(nodes[i], prevNodes[i]);
data.put(nodes[0], prevNodes[0]);
} else data.put(nodes[0], object);
}
return;
}
data.put(key, object);
}
public static void main(String[] args) {
path = "test.txt";
setup();
save();
load();
}
}
Normally it'll save integers from a bunch of other classes, then when the program is run again, loads it back into the appropriate variables. But for the sake of testing, all it does is print out the values.
//Settings
set("Settings.Difficulty.Level", 1);// not saving
set("Settings.Difficulty.Locked", 2);
set("Settings.Cheats.Enabled", 3); // not saving
set("Settings.Cheats.Locked", 4);
set("Settings.GUI.Enabled", 5);
This should save integers (1 to 5) to test.txt, and then prints them to the console
System.out.println(getInteger("Settings.Difficulty.Level"));
System.out.println(getInteger("Settings.Difficulty.Locked"));
System.out.println(getInteger("Settings.Cheats.Enabled"));
System.out.println(getInteger("Settings.Cheats.Locked"));
System.out.println(getInteger("Settings.GUI.Enabled"));
When I run the file, I expect to get the output of
1
2
3
4
5
But I actually get
-1
2
-1
4
5
Settings.Difficulty.Level and Settings.Cheats.Enabled doesnt even seem to be saved in the file at all.
Settings:
Difficulty:
Locked: 2
Cheats:
Locked: 4
GUI:
Enabled: 5
I'm pretty sure the issue is somewhere in the set method, but I'm not sure exactly what it is. I also don't know why its only two of the 5 variables that won't save (Must be something to do with the name used).
The error is here:
for (int i = 0; i <= nodes.length - 2; i++) {
if (data.containsKey(nodes[i]) && (data.get(nodes[i]) instanceof Map))
prevNodes[i] = new LinkedHashMap((Map) data.get(nodes[i]));
else if (!data.containsKey(nodes[i]))
prevNodes[i] = new LinkedHashMap();
}
This code is executed with the second set call. It finds "Settings" in data, but then, it does not find "Difficulty" in data (because that is in the "Settings" map). So it creates a new, empty LinkedHashMap. Then, this code happens:
prevNodes[prevNodes.length - 1].put(nodes[nodes.length - 1], object);
for (int i = prevNodes.length - 1; i >= 1; i--)
prevNodes[i - 1].put(nodes[i], prevNodes[i]);
It replaces the existing "Difficulty" node (which contains "Level") with the newly created one (which contains only "Locked"). Thus, "Level" is missing afterwards.
You can modify your for loop like this:
for (int i = 0; i <= nodes.length - 2; i++) {
final Map cur = (i == 0) ? data : prevNodes[i - 1];
if (cur.containsKey(nodes[i]) && (cur.get(nodes[i]) instanceof Map))
prevNodes[i] = new LinkedHashMap((Map) cur.get(nodes[i]));
else if (!cur.containsKey(nodes[i]))
prevNodes[i] = new LinkedHashMap();
}
But actually, the whole set method can be simplified: (Beware, this is untested code and may contain minor errors)
public static void set(String key, Object object) {
if (!exists())
return;
// no need to differentiate between paths with and without "."
final String[] nodes = key.split("\\.");
Map cur = data;
for (int i = 0; i <= nodes.length - 2; ++i) {
Object val = cur.get(nodes[i]);
if (val == null) {
val = new LinkedHashMap();
cur.put(nodes[i], val);
} else if (!(val instanceof Map)) {
// error in structure, handle it here (throw exception, …)
}
cur = (Map) val;
}
cur.put(nodes[nodes.length - 1], object);
}

What is the proper way to create a Hybrid Data structure of Ternary Search Trees

I am trying to create a class called HybridTST, where I can add multiple different TST's to a bigger data structure.
I have tried creating an array of Ternary Search Trees to a letter in the alphabet and then when I want to go to a specific TST I can iterate through the alphabet to find the correct TST. I am not sure if that the outcome is what I want. Am I creating a this Hybrid TST incorrectly?
public class HybridTST<E> implements TrieInterface
{
private TST[] myHybridTST = new TST[54];
private String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.'";
private int position = 0;
private int size;
HybridTST()
{
char[] alphabetArray = alphabet.toCharArray();
for (int i = 0; i<54; i++)
{
myHybridTST[i]= new TST(alphabetArray[i]);
}
}
#Override
public Object get(String key) {
if (key == null) {
throw new InvalidKeyException();
}
for (int i = 0; i < key.length(); i++) {
if (!Character.isLetter(key.charAt(i))) {
throw new InvalidKeyException();
}
}
position = 0;
for(char c: alphabet.toCharArray())
{
if(key.charAt(0)==c)
{
break;
}
position++;
}
return myHybridTST[position].get(key);
}
Here is the TST get portion:
public Object get(String key) {
if (key == null) {
throw new InvalidKeyException();
}
if (key == null)
throw new NullPointerException();
if(key!="aren't")
{
for (int i = 0; i < key.length(); i++) {
if (!Character.isLetter(key.charAt(i))) {
throw new InvalidKeyException();
}
}
}
Node x = get(root, key, 0);
if (x == null) return null;
return x.val;
}
private Node get(Node x, String key, int d) {
if (key == null) {
throw new InvalidKeyException();
}
if (key.length() == 0)
throw new IllegalArgumentException("key must have length >= 1");
if (x == null)
return null;
char c = key.charAt(d);
if (c<x.c)
{
return get(x.left, key, d);
}
else if(c>x.c)
{
return get(x.right, key, d);
}
else if(d < key.length()-1)
{
return get(x.mid, key, d+1);
}
else
{
return x;
}
}
Here is the test:
public void test10()
{
HybridTST<Integer> t = new HybridTST<Integer>();
t.put("A",new Integer(0));
t.put("AB",new Integer(1));
t.put("ABC",new Integer(2));
assertEquals( new Integer(0), t.get("A") );
assertEquals( new Integer(1), t.get("AB") );
assertEquals( new Integer(2), t.get("ABC") );
}
It its failing to get any items that I have put into the data structure.
My Hybrid TST PUT method:
public void put(String key, Object val) {
if (key == null) {
throw new InvalidKeyException();
}
for (int i = 0; i <1; i++) {
if (!Character.isLetter(key.charAt(i))) {
throw new InvalidKeyException();
}
}
int count = 0;
int position = 0;
position = 0;
for(char c: alphabet.toCharArray())
{
if(key.charAt(0)==c)
{
break;
}
position++;
}
size++;
myHybridTST[position].put(key, val);
}
In my TST class,
private static class Node {
private char c; // character
private Node left, mid, right; // left, middle, and right
// subtries
private Object val; // value associated with string
public Node[] next;
Node(char c) {
this.c = c;
}
}
public TST(char c) {
this.root = new Node(c);
}
I have no problem running your code, inserting and fetching values from the tree. However, it can be improved in some way:
Remove unused attributes
Use generics so you force the type of the elements you insert and fetch from the HybridTST and TST
Indentation is sometimes off
The code doesn't work as is (Node doesn't have method visit)
Instead of getting the position of the first letter on the alphabet, create a helper method for that.
Instead of calling new Integer(i), use Integer.valueOf(i)
From what I can see, your code contains the attribute of a 256-way trie plus the one for a ternary search tree, you should clean it

Hash table with linked list implementation and storing text file

I want to implement my own hash table using chaining and linked list but I am having a hard time figuring out how to use the implementation in the main method. I need to read a comma separated values file with data and store the names as keys and the two floating points as a value. I know I need to use object oriented programming but I having a difficult time accessing my data using my implementation.
Here is my code:
public class LinkedListHash{
String key;
String value;
LinkedListHash next;
public LinkedListHash(){
}
LinkedListHash(String key, String value){
this.key = key;
this.value = value;
this.next = null;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public String getKey(){
return key;
}
public LinkedListHash getNext(){
return next;
}
public void setNext(LinkedListHash next){
this.next = next;
}
class Hashtable {
int size = 0;
LinkedListHash[] table;
Hashtable(){
table = new LinkedListHash[size];
for (int i = 0; i < size; i++){
table[i] = null;
}
}
public String get(String key){
int hash = key.hashCode();
if (table[hash] == null){
return null;
}
else {
LinkedListHash input = table[hash];
while (input != null && input.getKey() != key){
input = input.getNext();
}
if (input == null){
return null;
}
else {
return input.getValue();
}
}
}
public void put(String key, String value){
int hash = key.hashCode();
if (table[hash] == null){
table[hash] = new LinkedListHash(key, value);
}
else {
LinkedListHash input = table[hash];
while (input.getNext() != null && input.getKey() != key){
input = input.getNext();
}
if (input.getKey() == key){
input.setValue(value);
}
else {
input.setNext(new LinkedListHash(key, value));
}
}
}
}
}
public static void main(String[] args) throws FileNotFoundException{
Hashtable<String, String> tbl = new Hashtable<String, String>();
String path = args[0];
if(args.length < 1) {
System.out.println("Error, usage: java ClassName inputfile");
System.exit(1);
}
Scanner reader = new Scanner(new FileInputStream(args[0]));
while((path = reader.nextLine()) != null){
String parts[] = path.split("\t");
tbl.put(parts[0], parts[1]);
} reader.close();
} }
Any way I could improve my code would be helpful.
Keep in mind I am not a very experienced programmer so I apologize for any horrendous mistakes.
Strings should not be compared with == or != unless you want to know if they are the same string occupying the same memory location. Use equals() instead.

Categories