How to implement a Linked List in Java?
Posted
by
nbarraille
on Stack Overflow
See other posts from Stack Overflow
or by nbarraille
Published on 2011-01-12T15:38:08Z
Indexed on
2011/01/12
15:53 UTC
Read the original article
Hit count: 137
Hello! I am trying to implement a simple HashTable in Java that uses a Linked List for collision resolution, which is pretty easy to do in C, but I don't know how to do it in Java, as you can't use pointers...
First, I know that those structures are already implemented in Java, I'm not planning on using it, just training here...
So I created an element, which is a string and a pointer to the next Element:
public class Element{
private String s;
private Element next;
public Element(String s){
this.s = s;
this.next = null;
}
public void setNext(Element e){
this.next = e;
}
public String getString(){
return this.s;
}
public Element getNext(){
return this.next;
}
@Override
public String toString() {
return "[" + s + "] => ";
}
}
Of course, my HashTable has an array of Element to stock the data:
public class CustomHashTable {
private Element[] data;
Here is my problem:
For example I want to implement a method that adds an element AT THE END of the linked List (I know it would have been simpler and more efficient to insert the element at the beginning of the list, but again, this is only for training purposes). How do I do that without pointer?
Here is my code (which could work if e was a pointer...):
public void add(String s){
int index = hash(s) % data.length;
System.out.println("Adding at index: " + index);
Element e = this.data[index];
while(e != null){
e = e.getNext();
}
e = new Element(s);
}
Thanks!
© Stack Overflow or respective owner