Why do you get a ConcurrentModificationException when using an iterator?

Problem : The java.util Collection classes are fail-fast, which means that if one thread changes a collection while another thread is traversing it through with an iterator the iterator.hasNext() or iterator.next() call will throw ConcurrentModificationException. Even the synchronized collection wrapper classes SynchronizedMap and SynchronizedList are only conditionally thread-safe, which means all individual operations are thread-safe but compound operations where flow of control depends on the results of previous operations may be subject to threading issues.

Solutions 1-3: for multi-thread access situation:

Solution 1: You can convert your list to an array with list.toArray() and iterate on the … Click here to continue reading.

How to implement collection ordering?

SortedSet and SortedMap interfaces maintain sorted order. The classes, which implement the Comparable interface, impose natural order. By implementing Comparable, sorting an array of objects or a collection (List etc) is as simple as:

For classes that don’t implement Comparable interface, or when one needs even more control over ordering based on multiple attributes, a Comparator interface should be used.

Comparable interface Comparator interface The “Comparable” allows itself to compare with another similar object (i.e. A class that implements Comparable becomes an object to be compared with). The method compareTo() is specified in the interface. The Comparator … Click here to continue reading.

Explain the Java Collections Framework?

The key interfaces used by the collections framework are List, Set and Map. The List and Set extends the Collection interface. Should not confuse the Collection interface with the Collections class which is a utility class.

Set (HashSet , TreeSet) List (ArrayList, LinkedList, Vector etc) A Set is a collection with unique elements and prevents duplication within the collection. HashSet and TreeSet are implementations of a Set interface. A TreeSet is an
ordered HashSet, which implements the SortedSet interface. A List is a collection with an ordered sequence of elements and may contain duplicates. ArrayList, LinkedList and Vector are … Click here to continue reading.

What is the difference between a stack and a queue?

Queue Stack First item to be inserted is the first one to be removed. Allows access to only last item inserted. This mechanism is called First In First Out (FIFO). An item is inserted or removed from one end called the “top” of the stack. This is called Last In First Out (LIFO) mechanism. Placing an item in the queue is called “enqueue or insertion” and removing an item from a queue is called “dequeue or deletion”. Pre J2SE 5.0, you should write your own Queue class with enqueue() and dequeue() methods using an ArrayList or a LinkedList class.
Click here to continue reading.