...

/

Lists, HashMap, HashSet, and TreeSet

Lists, HashMap, HashSet, and TreeSet

Learn about some minor methods from Collections Framework in Java.

Key components of the Java Collections Framework

We learned earlier that the Java Collections Framework has three key components that work together. The first is the interface.

The second is implementation, meaning classes that implement interfaces. We get objects from those classes on which algorithmic operations are performed.

The third and final is the algorithm. This is the final goal because algorithms in the Java Collections Framework are methods that perform useful computations, such as sorting, searching, shuffling, etc. Algorithms are polymorphic, which means the same method can be used by an Iterator object and a ListIterator object.

Press + to interact
The three components of the Java Collections Framework
The three components of the Java Collections Framework

We’ll see some examples in a bit.

Polymorphic add() method

Let’s see how the add() method works on different Collection objects.

Press + to interact
import java.util.*;
//CollectionOverall
class Main{
public static void main(String[] args) {
// ArrayList examples where we add elements
List<Object> arrayList = new ArrayList<Object>();
arrayList.add("Sanjib");
arrayList.add("JASON");
arrayList.add("John");
arrayList.add(10);
System.out.println(" ArrayList elements in tabular format: ");
System.out.print("\t" + arrayList);
// LinkedList examples where we add elements
List<Object> linkedList = new LinkedList<Object>();
linkedList.add("Sanjib");
linkedList.add("Jason");
linkedList.add("John");
linkedList.add(10);
System.out.println();
System.out.println(" LinkedList elements in tabular format: ");
System.out.print("\t" + linkedList);
// HashSet examples where we add elements
Set<Object> hashSet = new HashSet<Object>();
hashSet.add("Sanjib");
hashSet.add("Jason");
hashSet.add("John");
hashSet.add(10);
System.out.println();
System.out.println(" Set elements in tabular format: ");
System.out.print("\t" + hashSet);
// HashMap examples where we add elements
Map<Object,Object> hashMap = new HashMap<Object,Object>();
hashMap.put("Sanjib", "55");
hashMap.put("Jason", "45");
hashMap.put("John", "35");
System.out.println();
System.out.println(" Map elements in tabular format: ");
System.out.print("\t" + hashMap);
System.out.println();
}
}

The code above gives us the output below. From this output, we see that we ...