DEV Community

Cover image for Java Data Structures

Java Data Structures

Yegor Voronianskii on January 13, 2019

Interface List Exist two most used implementation of this interface it is ArrayList and LinkedList. Let's go deeper about each ...
Collapse
 
martinhaeusler profile image
Martin Häusler

A nice summary!

One small comment: a ConcurrentModificationException does not only occur when two threads access the same collection. It may also happen that your own (single-threaded) code iterates over a collection, and makes changes to it during the iteration.

For example:

for(Object element : collection){
    collection.remove(element);
}
Enter fullscreen mode Exit fullscreen mode

This snippet will always throw a ConcurrentModificationException (except for empty collections) even though only a single thread is at work. We are mutating the collection while an iterator is still active. Maybe specialized collections, such as the CopyOnWriteArrayList, can survive this loop without throwing an exception, but the general Collection contract specifies that this is an invalid case.

Collapse
 
vrnsky profile image
Yegor Voronianskii

Thank you, I am update the post

Collapse
 
hamidur01 profile image
Hamidur Rahman

Time complexity of TreeSet guarantees O(log n) not O(n)

Collapse
 
vrnsky profile image
Yegor Voronianskii

Oh, thank. You are true.

Collapse
 
hamidur01 profile image
Hamidur Rahman

Since LinkedHashSet is designed/implemented on a HashTable Structure it is possible to be O(1) but it can easily be O(n) depending on a hash()

Thread Thread
 
vrnsky profile image
Yegor Voronianskii

At the docs.oracle.com/javase/7/docs/api/... we see that is provide contant time for basic operation, and O(n) for iteration over a LinkedHashSet that means next require time proportional to the size of the set

Thread Thread
 
hamidur01 profile image
Hamidur Rahman

Then I think you meant constant time O(1) for add, contains, and remove. Iteration on any structure is always O(n).

Thread Thread
 
vrnsky profile image
Yegor Voronianskii • Edited

Yeah! for this operation I meant

Collapse
 
stealthmusic profile image
Jan Wedel

Thanks for the interesting article. Usually, I tend to use LinkedList when I mostly appending a lot of items of which the size I don’t know and/or when I iterate over all elements. When I’m doing a lot of random accesses, I use ArrayList. In your table, both list implementations have O(1), is that still true when the whole array needs to be copied due expansion? And what about actual time? Do you know any benchmarks for different use cases? I really would be interested.