Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusing java data structures

Tags:

java

Maybe the title is not appropriate but I couldn't think of any other at this moment. My question is what is the difference between LinkedList and ArrayList or HashMap and THashMap .

Is there a tree structure already for Java(ex:AVL,red-black) or balanced or not balanced(linked list). If this kind of question is not appropriate for SO please let me know I will delete it. thank you

like image 574
London Avatar asked Aug 25 '26 11:08

London


2 Answers

ArrayList and LinkedList are implementations of the List abstraction. The first holds the elements of the list in an internal array which is automatically reallocated as necessary to make space for new elements. The second constructs a doubly linked list of holder cells, each of which refers to a list element. While the respective operations have identical semantics, they differ considerably in performance characteristics. For example:

  • The get(int) operation on an ArrayList takes constant time, but it takes time proportional to the length of the list for a LinkedList.

  • Removing an element via the Iterator.remove() takes constant time for a LinkedList, but it takes time proportional to the length of the list for an ArrayList.

The HashMap and THashMap are both implementations of the Map abstraction that are use hash tables. The difference is in the form of hash table data structure used in each case. The HashMap class uses closed addressing which means that each bucket in the table points to a separate linked list of elements. The THashMap class uses open addressing which means that elements that hash to the same bucket are stored in the table itself. The net result is that THashMap uses less memory and is faster than HashMap for most operations, but is much slower if you need the map's set of key/value pairs.

For more detail, read a good textbook on data structures. Failing that, look up the concepts in Wikipedia. Finally, take a look at the source code of the respective classes.

like image 113
Stephen C Avatar answered Aug 27 '26 03:08

Stephen C


Read the API docs for the classes you have mentioned. The collections tutorial also explains the differences fairly well.

java.util.TreeMap is based on a red-black tree.

like image 34
Michael Borgwardt Avatar answered Aug 27 '26 03:08

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!