Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement a Linked List in Java?
    primarykey
    data
    text
    <p>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...</p> <p>First, I know that those structures are already implemented in Java, I'm not planning on using it, just training here...</p> <p>So I created an element, which is a string and a pointer to the next Element:</p> <pre><code>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 + "] =&gt; "; } } </code></pre> <p>Of course, my HashTable has an array of Element to stock the data:</p> <pre><code>public class CustomHashTable { private Element[] data; </code></pre> <p>Here is my problem:</p> <p>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?</p> <p>Here is my code (which could work if e was a pointer...):</p> <pre><code>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); } </code></pre> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload