Java Collection
In this post, I will talk about Java collection. Some well-known containers such as ArrayList, TreeSet are implementing classes of their respective interfaces which inherit from the collection interface. Therefore, it is a good idea to learn methods from the collection interface because all of its derived implementing classes will acquire the same methods.
Collection is a kind of container provided by Java. It stores objects and can change its length.
List Interface (Vector / ArrayList / LinkedList)
- Elements are ordered
- Allow duplicated values
- Can use index to traversal elements
Set Interface (TreeSet / HashSet / LinkedHashSet)
- Elements in TreeSet and HashSet are not ordered
- Does not allow duplicated values
- Can not use index to traversal elements
Collection Interface
- Can not use index to traversal elements
Commonly Used Methods in Collection Interface
// add() method: add an element to a collection
private static void demo01() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
System.out.println(coll); // [Hello, World]
}
// remove() method: delete an element from a collection
private static void demo02() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
coll.remove("Hello");
System.out.println(coll); // [World]
}
// contains(): check if the collection contains the element
private static void demo03() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
System.out.println(coll.contains("Hello")); // true
System.out.println(coll.contains("Hey")); // false
}
// isEmpty(): check if the collection is empty or not
private static void demo04() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
System.out.println(coll.isEmpty()); // true
}
// size(): returns the number of elements in the collection
private static void demo05() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
System.out.println(coll.size()); // 2
}
// toArray(): Store elements of the collection into an array
private static void demo06() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
Object[] arr = coll.toArray();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
// clear(): clear all elements of the collection
private static void demo07() {
Collection<String> coll = new ArrayList<>(); // Polymorphism
coll.add("Hello");
coll.add("World");
coll.clear();
System.out.println(coll); // []
}