java collections

Enumerated Collection enumeration()

With legacy classes (JDK 1.0 DS) we use Enumeration. With collections framework classes we use Iterator or ListIterator. As such, with collection classes it is not possible to use Enumeration. To overcome this, the Collections class comes with enumeration() method. It returns collection class elements as an Enumeration. It is…

How many times element occurs with frequency()

In a data structure (that accepts duplicate elements), an element can exist any number of times as in the case of ArrayList etc. The frequency() method is useful to find out how many times the same element exist in a data structure. Following is the method signature static int frequency(Collection…

Singleton List with singletonList()

What is singleton? With singleton class, you can create only one object. If another object is tried to create, the JVM throws UnsupportedOperationException. A Singleton class contains only one element. If tried to add a second element, the add() method throws UnsupportedOperationException. Singleton class limits the developer from instantiating more…

Java Rotate elements with rotate()

The Collections algorithms includes a typical method rotate() that rotates the elements in cyclic order. After the last few elements, the first elements can be moved. This method is useful to change the order of elements. Note, it is not swapping or shuffling. In shuffling, elements are moved in between…

Copy one list to another with copy()

The Collections.copy() method takes two list objects as parameters. The first one is the destination list and the second is the source list. The source list elements are copied into target list. Here, copy operation does actually replacement. Following is the method signature static void copy(List destination1, List source1): Copies…

Java Swap two elements with swap()

The Collections method swap() is very useful to swap two values in a programming code. For example, the prices of two different dates can be swapped. This method comes into existence with JDK 1.4. Following is the method signature of swap() method static void swap(List list1, int index1, int index2):…

Collections Hierarchy Java

After knowing the meaning and purpose of Collections framework, let us know the basic interfaces, derived classes and their properties. Java data structures are nothing but subclasses of Collection and Map interfaces. Following hierarchy gives all the interfaces of Collections framework. Fig: Basic interfaces of collections framework Map and SortedMap…