Parametrized object cannot be resolved to variable [duplicate] - java

This question already has answers here:
scope error in if statement in java program
(3 answers)
Closed 7 years ago.
I have this piece of code:
#SuppressWarnings("unchecked")
public void put(K key,V value){
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
}
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}
Variables candidate and slotNumber are underlined in Eclipse, as are the invocations of the TableEntry() constructor. Can you tell me why I can't compare for example candidate with null?
If you need, here is complete class (Hash table):
package hr.fer.oop.lab3.prob2;
public class SimpleHashtable<K,V> {
private V[] elements;
private static int defaultsize = 16;
private int size;
public SimpleHashtable(){
this(defaultsize);
}
#SuppressWarnings("unchecked")
public SimpleHashtable(int initialCapacity){
if(initialCapacity < 1) {
throw new IllegalArgumentException("Capacity must be at least 1.");
}
elements = (V[])new Object[calculateCapacity(initialCapacity)];
}
public int calculateCapacity(int number){
int result = 2;
while(result < number){
result = result << 1;
}
System.out.println(result);
return result;
}
#SuppressWarnings("unchecked")
public void put(K key,V value){
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
}
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}
#SuppressWarnings("unchecked")
private TableEntry<K,V> getTableEntry(K key) {
int slotNumber = Math.abs(key.hashCode()) % this.size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
while(candidate != null){
if(key.equals(candidate.getKey())){
return candidate;
}
candidate = candidate.next;
}
return null;
}
private boolean containsKey(K key) {
return false;
}
private static class TableEntry<K,V>{
K key;
V value;
TableEntry next = null;
public TableEntry(K key, V value, TableEntry next){
this.key = key;
this.value = value;
this.next = next;
}
K getKey(){
return key;
}
V getValue(){
return value;
}
void setValue(V value){
this.value = value;
}
#Override
public String toString(){
return "Key:" + (String)key + "Value:" + (String)value;
}
}
}

Your declarations of the candidate and slotNumber variables are visible only within the innermost block containing them, which in this case contains nothing else. It looks like you want to move the code that uses those variables into that block (as opposed to moving the declarations out of it):
#SuppressWarnings("unchecked")
public void put(K key, V value){
if (this.containsKey(key)) {
TableEntry<K, V> foundKey = this.getTableEntry(key);
foundKey.setValue(value);
} else {
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K, V>) elements[slotNumber];
// empty slot
if (candidate == null) {
elements[slotNumber] = new TableEntry<K, V>(key, value, null);
} else {
while (candidate != null) {
candidate = candidate.next;
}
candidate.next = new TableEntry<K, V>(key, value, null);
}
}
}

You can't compare then - nor access them at all - at those locations because they're out of scope. You have declared them within the 'else' part of your if-statement, so that's their scope.
So, solutions are to either move the declaration outside the if, or move your code to inside that 'else' code block. Which you choose depends on whether you want to access 'slotNumber' or 'candidate' subsequently; if not, then personally I'd prefer the second, so :
if(this.containsKey(key)){
TableEntry<K,V> foundKey = (TableEntry<K,V>)this.getTableEntry(key);
foundKey.setValue(value);
} else{
int slotNumber = Math.abs(key.hashCode()) % size;
TableEntry<K,V> candidate = (TableEntry<K,V>) elements [slotNumber];
// empty slot
if(candidate == null){
elements[slotNumber] = new TableEntry(key,value,null);
}else{
while(candidate != null){
candidate = candidate.next;
}
candidate.next = new TableEntry(key,value,null);
}
}

Related

B-Tree implementing toString method in Node Class that is giving this error: Cannot invoke forEach((<no type> c) -> {}) on the array type Node<E>[]]

I have Implemented B-Tree, I have given toString to Implement method in Node class as it but its giving errot in this line children.forEach(c ->builder.append(c.toString(depth + 1))); I have tried various methods but not worked
here is other B-Tree files and pdf where is given toString Methods and other Instruction check out these files
toString code
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Node<E extends Comparable<E>> {
public int nodeLocation;
public int index;
private E[] keys = null;
int keysSize = 0;
public Node<E>[] children = null;
public Node<E>[] elements;
int childrenSize = 0;
private Comparator<Node<E>> comparator = new Comparator<Node<E>>() {
#Override
public int compare(Node<E> arg0, Node<E> arg1) {
return arg0.getKey(0).compareTo(arg1.getKey(0));
}
};
protected Node<E> parent = null;
Node(Node<E> parent, int maxKeySize, int maxChildrenSize) {
this.parent = parent;
this.keys = (E[]) new Comparable[maxKeySize + 1];
this.keysSize = 0;
this.children = new Node[maxChildrenSize + 1];
this.childrenSize = 0;
}
E getKey(int index) {
return keys[index];
}
int indexOf(E value) {
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value))
return i;
}
return -1;
}
void addKey(E value) {
keys[keysSize++] = value;
Arrays.sort(keys, 0, keysSize);
}
E removeKey(E value) {
E removed = null;
boolean found = false;
if (keysSize == 0)
return null;
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value)) {
found = true;
removed = keys[i];
} else if (found) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
}
if (found) {
keysSize--;
keys[keysSize] = null;
}
return removed;
}
E removeKey(int index) {
if (index >= keysSize)
return null;
E value = keys[index];
for (int i = index + 1; i < keysSize; i++) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
keysSize--;
keys[keysSize] = null;
return value;
}
int numberOfKeys() {
return keysSize;
}
Node<E> getChild(int index) {
if (index >= childrenSize)
return null;
return children[index];
}
int indexOf(Node<E> child) {
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child))
return i;
}
return -1;
}
boolean addChild(Node<E> child) {
child.parent = this;
children[childrenSize++] = child;
Arrays.sort(children, 0, childrenSize, comparator);
return true;
}
boolean removeChild(Node<E> child) {
boolean found = false;
if (childrenSize == 0)
return found;
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child)) {
found = true;
} else if (found) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
}
if (found) {
childrenSize--;
children[childrenSize] = null;
}
return found;
}
Node<E> removeChild(int index) {
if (index >= childrenSize)
return null;
Node<E> value = children[index];
children[index] = null;
for (int i = index + 1; i < childrenSize; i++) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
childrenSize--;
children[childrenSize] = null;
return value;
}
int numberOfChildren() {
return childrenSize;
}
/**
* {#inheritDoc}
*/
public String toStringg() {
return toString(0);
}
// // based on what toString() does, think about what ‘elements’ and ‘children’
// can be
private String toString(int depth) {
StringBuilder builder = new StringBuilder();
String blankPrefix = new String(new char[depth]).replace("\0", "\t");
List<String> printedElements = new LinkedList<>();
for (Node<E> e : elements)
printedElements.add(e.toString());
String eString = String.join(" :: ", printedElements);
builder.append(blankPrefix).append(eString).append("\n");
children.forEach(c -> builder.append(c.toString(depth + 1))); // this line is giving error
return builder.toString();
}
}
I Have Gievn pdf File where is gievn insructions and code implement I have tried to change childern but not worked I am bound to not make changes in gievn toString method
Arrays in Java doesn't declare their own behavior (don't try to reproduce your experience from languages like JavaScript and TypeScript, where Arrays have methods).
Therefore, you can't invoke method forEach() on the children array (this method is accessible with implementations of Iterable interface, like Collections).
You can use an enhanced for-loop instead:
for (Node<E> node : children) {
builder.append(node.toString(depth + 1));
}
Alternatively, if you declare the property children as a List you'll be able use forEach() with it:
public List<Node<E>> children;
Judging by your assignment requirements, that what you're expected to do.
That would require changing all the methods that make use of children because you can't dial with a List in the same way as with an array. I.e. you would need to use the behavior of the List interface.
children[i] would turn to children.get(i). And children[i] = ... would become children.set(i, ...), or children.add(...).

How do I fix this ArrayIndexOutOfBoundsException in my hashtable?

I was wondering if anyone could help me this ArrayIndexOutOfBoundsException that occurs when trying to run a tester class.
The exception occurs at the remove method within the hashtable file. I have tried switching out my code with my friend's code but that didn't work either.
Any help would be greatly appreciated
===========================================================================
Here is the HashTable :
public class HashTable {
Object[] hTable;
int mSize;
int size;
HashTable() {
mSize = 101;
hTable = new Object[mSize];
}
HashTable(int initCap) {
mSize = initCap;
}
Object put(Object key, Object value) {
if (size == mSize) {
throw new IllegalStateException("No room within the hashtable");
}
int hashC = key.hashCode();
int index = hashC % mSize;
size++;
while (index < hTable.length) {
if (hTable[index] == null) {
hTable[index] = new Entry(key, value);
size++;
return null;
} else if (((Entry) hTable[index]).key.equals(key)) {
Object prevVal = ((Entry) hTable[index]).val;
hTable[index] = new Entry(key, value);
return prevVal;
} else if (((Entry) hTable[index]).rCheck) {
hTable[index] = new Entry(key, value);
while (index < hTable.length) {
index++;
if (hTable[index] == null) {
size++;
return null;
} else if (((Entry) hTable[index]).key.equals(key)) {
Object prevVal = ((Entry) hTable[index]).val;
((Entry) hTable[index]).remove();
return prevVal;
}
}
}
index++;
}
if (hTable[index] == null) {
hTable[index] = new Entry(key, value);
return null;
} else {
Object oldEntry = ((Entry) hTable[index]).val;
hTable[index] = new Entry(key, value);
return oldEntry;
}
}
Object get(Object key) {
int hashC = key.hashCode();
int index = hashC % mSize;
return ((Entry) hTable[index]).val;
}
Object remove(Object key) {
int hashC = key.hashCode();
int index = hashC % mSize;
Object returnObj = null;
while (hTable[index] != null) { //here is where the OutOfBounds error occurs
if (((Entry) hTable[index]).key.equals(key)) {
returnObj = ((Entry) hTable[index]).val;
((Entry) hTable[index]).remove();
size--;
break;
}
index++;
}
return returnObj;
}
int size() {
return size;
}
#Override
public String toString() {
String returnString = "";
for (int i = 0; i < hTable.length; i++) {
if (hTable[i] == null || ((Entry) hTable[i]).rCheck) {
returnString += "dummy\n";
continue;
}
returnString += "Index: " + i +
" \n Key: " + ((Integer) (((Entry) hTable[i]).key)).intValue() % 101 +
"\nValue: " + (String) (((Entry) hTable[i]).val) +
"\n++++++++++++++++++++++++++++++++++++++++++++++\n";
}
return returnString;
}
private class Entry {
Object key;
public boolean rCheck;
public Object val;
Entry() {
key = null;
val = null;
rCheck = false;
}
Entry(Object k, Object v) {
key = k;
val = v;
rCheck = false;
}
Object value() {
return val;
}
Object key() {
return key;
}
void remove() {
rCheck = true;
}
public String toString() {
return "";
}
}
}
Here is the hash table tester:
import java.io.*;
import java.util.*;
public class hashTest {
public static void main(String args[]) throws FileNotFoundException {
HashTable hashTable = new HashTable();
Scanner fileRead = new Scanner(new File("data1.txt"));
while(fileRead.hasNext()) {
Object key = fileRead.next();
fileRead.next();
Object value = fileRead.nextLine();
hashTable.put(key, value);
System.out.println(hashTable.get(key));
}
Scanner fileRead2 = new Scanner(new File("data2.txt"));
while(fileRead2.hasNext()){
Object key = fileRead2.next();
hashTable.remove(key);
fileRead2.nextLine();
}
Scanner fileRead3 = new Scanner(new File("data3.txt"));
while(fileRead3.hasNext()){
Object key = fileRead3.next();
fileRead3.next();
Object value = fileRead3.nextLine();
hashTable.put(key, value);
}
Scanner fileRead4 = new Scanner(new File("data4.txt"));
while(fileRead4.hasNext()){
Object key = fileRead4.next();
fileRead4.next();
Object value = fileRead4.nextLine();
hashTable.put(key, value);
}
}
}
===========================================================================
In the shared google drive link below you will find a zip containing data inputs.
https://drive.google.com/file/d/1iYrzWl9mtv_io3q7K1_m2EtPFUXGbC3p/view?usp=sharing
Your Problem is at this code block:
while (index < hTable.length) {
index++;
if (hTable[index] == null)...
At the last iteration index will be the same as hTable.length. In your Example index will be 100 where the condition will be accepted. In the next step index will be incremented: index = 101. At hTable[101] the ArrayIndexOutOfBoundsException will occur.

Java HashMap: Changing Bucket Implementation to Linear Probing method

In advance, I apologize for my lack of experience, these are advanced concepts that are difficult to wrap my head around. From what I understand, linear probing is circular, it won't stop until it finds an empty cell.
However I am not sure how to implement it. Some example on how to would be greatly appreciated. Sorry again for the inexperience, I'm not some vetted programmer, I'm picking this up very slowly.
public boolean ContainsElement(V element)
{
for(int i = 0; i < capacity; i++)
{
if(table[i] != null)
{
LinkedList<Entry<K, V>> bucketMethod = table[i];
for(Entry<K, V> entry : bucketMethod)
{
if(entry.getElement().equals(element))
{
return true;
}
}
}
}
return false;
}
Here's a working hash table based on the pseudocode examples found in the Wikipedia article for open addressing.
I think the main differences between the Wikipedia example and mine are:
Treating the hashCode() a little bit due to the way Java does modulo (%) with negative numbers.
Implemented simple resizing logic.
Changed the logic in the remove method a little bit because Java doesn't have goto.
Otherwise, it's more or less just a direct translation.
package mcve;
import java.util.*;
import java.util.stream.*;
public class OAHashTable {
private Entry[] table = new Entry[16]; // Must be >= 4. See findSlot.
private int size = 0;
public int size() {
return size;
}
private int hash(Object key) {
int hashCode = Objects.hashCode(key)
& 0x7F_FF_FF_FF; // <- This is like abs, but it works
// for Integer.MIN_VALUE. We do this
// so that hash(key) % table.length
// is never negative.
return hashCode;
}
private int findSlot(Object key) {
int i = hash(key) % table.length;
// Search until we either find the key, or find an empty slot.
//
// Note: this becomes an infinite loop if the key is not already
// in the table AND every element in the array is occupied.
// With the resizing logic (below), this will only happen
// if the table is smaller than length=4.
while ((table[i] != null) && !Objects.equals(table[i].key, key)) {
i = (i + 1) % table.length;
}
return i;
}
public Object get(Object key) {
int i = findSlot(key);
if (table[i] != null) { // Key is in table.
return table[i].value;
} else { // Key is not in table
return null;
}
}
private boolean tableIsThreeQuartersFull() {
return ((double) size / (double) table.length) >= 0.75;
}
private void resizeTableToTwiceAsLarge() {
Entry[] old = table;
table = new Entry[2 * old.length];
size = 0;
for (Entry e : old) {
if (e != null) {
put(e.key, e.value);
}
}
}
public void put(Object key, Object value) {
int i = findSlot(key);
if (table[i] != null) { // We found our key.
table[i].value = value;
return;
}
if (tableIsThreeQuartersFull()) {
resizeTableToTwiceAsLarge();
i = findSlot(key);
}
table[i] = new Entry(key, value);
++size;
}
public void remove(Object key) {
int i = findSlot(key);
if (table[i] == null) {
return; // Key is not in the table.
}
int j = i;
table[i] = null;
--size;
while (true) {
j = (j + 1) % table.length;
if (table[j] == null) {
break;
}
int k = hash(table[j].key) % table.length;
// Determine if k lies cyclically in (i,j]
// | i.k.j |
// |....j i.k.| or |.k..j i...|
if ( (i<=j) ? ((i<k)&&(k<=j)) : ((i<k)||(k<=j)) ) {
continue;
}
table[i] = table[j];
i = j;
table[i] = null;
}
}
public Stream<Entry> entries() {
return Arrays.stream(table).filter(Objects::nonNull);
}
#Override
public String toString() {
return entries().map(e -> e.key + "=" + e.value)
.collect(Collectors.joining(", ", "{", "}"));
}
public static class Entry {
private Object key;
private Object value;
private Entry(Object key, Object value) {
this.key = key;
this.value = value;
}
public Object getKey() { return key; }
public Object getValue() { return value; }
}
public static void main(String[] args) {
OAHashTable t = new OAHashTable();
t.put("A", 1);
t.put("B", 2);
t.put("C", 3);
System.out.println("size = " + t.size());
System.out.println(t);
t.put("X", 4);
t.put("Y", 5);
t.put("Z", 6);
t.remove("C");
t.remove("B");
t.remove("A");
t.entries().map(e -> e.key)
.map(key -> key + ": " + t.get(key))
.forEach(System.out::println);
}
}
java.util.HashMap implementation of java.util.Map internally provides linear probing that is HashMap can resolve collisions in hash tables.

inheritance and recursive data structures (trees): identical child class with one method removed behaves differently

I implemented a binary search tree and would like to make a subclass that is self-balancing (AVL). I was getting strange results, and so I decided, to isolate the problem, I made an exact copy of the parent class MyTreeMap, and called it dumbchild extends MyTreeMap. Again, it's exactly the same and works correctly. Then I delete one of the methods in dumbchild expecting it to inherit it from MyTreeMap, and that changed the behavior of the class.
This seems like a very straightforward application of inheritance, but it's not working. I thought maybe it could have to do with the data structure being recursive.
EDIT: it was requested that I include all of the code
import java.util.Iterator;
public class MyTreeMap<K extends Comparable<? super K>, V> implements Iterable<K>{
public K key;
public V value;
public int height = 0;
public MyTreeMap<K, V> left, right;
protected void setHeight(){ // if key is not null, left and right should not be null
if(key == null){
height = 0;
}
else{
height = 1 + Math.max(left.height, right.height);
}
System.out.println("set of " + key + " height to " + height);
}
public V put(K key, V value){
if(key == null){
throw new NullPointerException();
}
V ret;
if(this.key == null){ // empty leaf, place found
this.key = key;
this.value = value;
left = new MyTreeMap<>();
right = new MyTreeMap<>();
ret = null;
}
else{
int compare = key.compareTo(this.key);
if(compare == 0){ //replace
this.value = value;
ret = value;
}
else if(compare < 0){ // put to left
ret = left.put(key, value);
}
else{
ret = right.put(key, value);
}
}
setHeight();
return ret;
}
public Iterator<K> iterator(){
return new Iterator<K>(){
Iterator<K> l, r;
K current = MyTreeMap.this.key;
{
if(left != null) l = left.iterator();
if(right != null) r = right.iterator();
}
public boolean hasNext(){
return current != null;
}
public K next(){
K ret = current;
if(l!= null && l.hasNext()){
current = l.next();
}
else if(r!= null && r.hasNext()){
current = r.next();
}
else{
current = null;
}
return ret;
}
};
}
public static void main(String[] args){
MyTreeMap<Integer, String> t = new MyTreeMap<>();
for(int i = 0; i<64; i++){
t.put(i, null);
}
Iterator<Integer> it = t.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("height: " + t.height);
}
}
and here is dumbchild's declaration:
public class dumbchild<K extends Comparable<? super K>, V> extends MyTreeMap<K, V> implements Iterable<K>{
dumbchild does not have setHeight, but it is exactly the same in every other way (copied and pasted, replace "MyTreeMap" text with "dumbchild"). They even have the same main method for testing.
The test is to add a bunch of stuff, and then iterator through it in preorder, printing out the values, and then print the height.
MyHashMap prints the correct height, dumbchild prints 0. If I remove other methods from dumbchild, other things go wrong too.
What am I missing?
Thanks
I tested with the following code, and dumbchild correctly prints the height as 64. Was there any problem originally? All I did is to add definition of remove() in the code that returning an anonymous instance of Iterator<T>.
import java.util.Iterator;
class dumbchild<K extends Comparable<? super K>, V> extends MyTreeMap<K, V> implements Iterable<K>{
}
public class MyTreeMap<K extends Comparable<? super K>, V> implements Iterable<K>{
public K key;
public V value;
public int height = 0;
public MyTreeMap<K, V> left, right;
protected void setHeight(){ // if key is not null, left and right should not be null
if(key == null){
height = 0;
}
else{
height = 1 + Math.max(left.height, right.height);
}
System.out.println("set of " + key + " height to " + height);
}
public V put(K key, V value){
if(key == null){
throw new NullPointerException();
}
V ret;
if(this.key == null){ // empty leaf, place found
this.key = key;
this.value = value;
left = new MyTreeMap<>();
right = new MyTreeMap<>();
ret = null;
}
else{
int compare = key.compareTo(this.key);
if(compare == 0){ //replace
this.value = value;
ret = value;
}
else if(compare < 0){ // put to left
ret = left.put(key, value);
}
else{
ret = right.put(key, value);
}
}
setHeight();
return ret;
}
public Iterator<K> iterator(){
return new Iterator<K>() {
Iterator<K> l, r;
K current = MyTreeMap.this.key;
{
if(left != null) l = left.iterator();
if(right != null) r = right.iterator();
}
public boolean hasNext(){
return current != null;
}
public K next(){
K ret = current;
if(l!= null && l.hasNext()){
current = l.next();
}
else if(r!= null && r.hasNext()){
current = r.next();
}
else{
current = null;
}
return ret;
}
#Override
public void remove() {
// ?
}
};
}
public static void main(String[] args){
/*
MyTreeMap<Integer, String> t = new MyTreeMap<>();
for(int i = 0; i<64; i++){
t.put(i, null);
}
Iterator<Integer> it = t.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("height: " + t.height);
*/
dumbchild<Integer, String> c = new dumbchild<>();
for(int i = 0; i<64; i++){
c.put(i, null);
}
Iterator<Integer> ct = c.iterator();
while(ct.hasNext()){
System.out.println(ct.next());
}
System.out.println("height: " + c.height);
}
}

Simple HashTable implementation using an array in Java?

I'm having a problem with implementing a very simple HashTable using an array. The problem is that the first Item put in the HashTable is always AVAILABLE. Maybe you guys can see what is going wrong. This is the HashTable class:
public class HashTable {
private Item[] data;
private int capacity;
private int size;
private static final Item AVAILABLE = new Item("Available", null);
public HashTable(int capacity) {
this.capacity = capacity;
data = new Item[capacity];
for(int i = 0; i < data.length; i++) {
data[i] = AVAILABLE;
}
size = 0;
}
public int size() {
return size;
}
public int hashThis(String key) {
return key.hashCode() % capacity;
}
public Object get(String key) {
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
return data[hash].element();
}
public void put(String key, Object element) {
if(key != null) {
size++;
int hash = hashThis(key);
while(data[hash] != AVAILABLE && data[hash].key() != key) {
hash = (hash + 1) % capacity;
}
data[hash] = new Item(key, element);
}
}
public Object remove(String key) {
// not important now.
throw new UnsupportedOperationException("Can't remove");
}
public String toString() {
String s = "<HashTable[";
for(int i = 0; i < this.size(); i++) {
s += data[i].toString();
if(i < this.size() - 1) {
s += ",";
}
}
s += "]>";
return s;
}
}
For more clarity, this is the Item class:
public class Item {
private String key;
private Object element;
public Item(String key, Object element) {
this.setKey(key);
this.setElement(element);
}
public String key() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object element() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public String toString() {
String s = "<Item(";
s += this.key() + "," + this.element() + ")>";
return s;
}
}
To give an example:
HashTable ht = new HashTable(10);
ht.put("1", "a");
The output of toString() after putting has to be:
"<HashTable[<Item(1,a)>]>"
but I get:
"<HashTable[<Item(Available,null)>]>"
update: I should probably mention that the next Item gets put correctly and the one after that is not again.
I think the problem is in your toString method. You loop for 0 - size when size = 1 so once so you only print out the first value in your hashTable problem is the first value in your hash table is not a real value it's an AVAILABLE you have to do something like this
EDIT: Sorry I forgot to move the index over.
public String toString() {
String s = "<HashTable[";
int i = 0;
int count = 0;
while(count < this.size()) {
//Skip the AVAILABLE cells
if(data[i] == AVAILABLE) {
i++;
continue;
}
s += data[i].toString();
if(count < this.size() - 1) {
s += ",";
}
count++;
}
s += "]>";
return s;
}
Try this for toString() if still interested in the solution, I ran it and its fine:
public String toString()
{
String s = "<HashTable[";
for (int i = 0; i < this.capacity; i++)
{
if (data[i].Element != null)
{
s += data[i].toString();
if (i < this.size - 1)
{
s += ",";
}
}
}
s += "]>";
return s;
}

Categories

Resources