-->
Let me put it in basic way :
Collections is nothing but a backpack, guess what are the things you can store in a backpack.
Probably you must have guessed everything that we can store in backpack, but let list few of them : 1. Laptop, Mouse, HeadPhones, earPhones, Mouse (computer's and animal too), Book, Notepad, pen, pencil you can write so on.
Almost you can store everything, you cannot store elephant though.
Within the backpack's size you can store all the things.
Lets' discuss about Java Collection : Collection is a framework which manipulates only one data type, which is god data type of Java.
I mean data type of
Collections in java is a framework that provides an architecture to store and manipulate the group of objects Collections in java is a framework that provides an architecture to store and manipulate the group of objects
I am not going to discuss everything present in collection, but only collection that we use frequently and which are :
List is an ordered collection and can contain duplicate elements. You can access any element from its index.
List is more like array with dynamic length, List is one of the most used Collection type.
Similar to library the list collection also stores the objects based on the index number, and it can also store duplicate objects as the access is going to happen through index.
List is a interface, and it just provides what should be present if somebody implements the interface, so the list interface will not have any implementations.
ArrayList and LinkedList classes provide implementation to the List interface methods, the methods present in the ArrayList and LinkedList are same with little changes
There are few frequently used methods in java list, I would be discussing them:
This method adds an element/value into the list based on the index. Here the index is calculated automatically based on the number of existing elements
In below code, String value will be stored as Object type only and the value will be stored at the last position in the list.
obj.add("karthiq")
This add method adds the given value and accepts two parameter; one the index where you want to add the value, two Object O is the value to be added.
You will face
obj.add(2, boolean)
Remove method is overloaded method, There are two remove() methods in List.
First remove method accepts a index of int type and removes a object at the given position., Second remove() method accepts value of object type and removes the value by searching the total list one by one till it finds the matching element.
After removing an element the element after that index will move one step closer to the beginning of the list.
obj.remove(int index) // faster
obj.remove(Object o) // slower
set method updates the element value at a given index, set method doesnot return any value.
obj.set(4, "karthiQ")
// sets element at index 4 to "karthiQ"
indexOf method retrieves the index of the first matching object o. If the element is not found in the list then this method returns the value -1.
indexOf method returns int values
obj.indexOf("karthiQ")
get fetches the value at a given position, returns Object value.
obj.get(2); // retrieves the value at position 2
size() method works based on the number of elements in the list.
The size() method returns the counter , so we would have the number of elements present in the list as output.
size() method returns int value.
obj.size(); // total number of elements in the list
contains() method checks whether the given element is present in the list or not.
If element is present then contains() method results in true otherwise false
obj.contains("karthiQ");
clear() method is used for removing all the elements of the list in one go, this will not delete the list but elements in the list.
obj.clear();
Complete program for the list operations.
package cherchertech;
import java.util.ArrayList;
import java.util.List;
public class OverLoading {
public static void main(String[] args) {
List al = new ArrayList();
al.add("chercher tech");
al.add(true);
al.add(10);
al.add(new ArrayList());
System.out.println("value at index 2 before Adding value at 2 : " +al.get(2));
al.add(2, 20);
System.out.println("value at index 2 after Adding value at 2 : " +al.get(2));
al.remove("chercher tech"); // based on object
System.out.println("All values in list : " +al);
al.remove(1); // based on index
System.out.println("All values in list : " +al);
al.set(1, "eee");
System.out.println("Value at index 1 :" +al.get(1));
System.out.println("index of avengers (none present): "+ al.indexOf("Avenger"));
System.out.println("get the value at index 0 " +al.get(0));
System.out.println("Number of elements present in the list : "+al.size());
System.out.println("does list contains 'eee' : "+al.contains("eee"));
al.clear();
System.out.println("Elements present in list after clearing the list :" +al );
}
}
Output of the above program is :
value at index 2 before Adding value at 2 : 10
value at index 2 after Adding value at 2 : 20
All values in list : [true, 20, 10, []]
All values in list : [true, 10, []]
Value at index 1 :eee
index of avengers (none present): -1
get the value at index 0 true
Number of elements present in the list : 3
does list contains 'eee' : true
Elements present in list after clearing the list :[]
The Set interface extends the Collection interface. It will make sure that an instance of Set contains no duplicate elements.
The subclasses class implements hashcode and equals methods to make sure uniqueness of objects.
Three concrete classes of Set are HashSet, LinkedHashSet and TreeSet
Set stores the values in random order and accessing the elements happens through element Value rather than index.
HashSet, LinkedHashSet, TreeSet are the classes which implement the Set interface
We will discuss about most used methods in the Set type of collection in java.
add() method adds an element to the set if it is not already present.
addAll() method Adds all of the elements in the specified list to the set if they are not already present.
Adds all of the elements in the specified set to the set that calls the method if they are not already present.
clear() method removes all of the elements present in the set.
clone() creates a duplicate copy of the set.
contains() method returns true if the set contains the specified element otherwise false.
containsAll method returns true if the set contains all of the elements in the specified list. The list must be of the same type as the set that calls the method.
Returns true if the set contains all of the elements in the specified set. The specified set must be of the same type as the original set that calls the method.
Compares this set with the specified set and returns true if both sets are equal; otherwise, returns false.
isEmpty() method returns true if the set has zero elements, other wise false.
Removes the specified element from the set if it is present.
Removes the elements in the specified list from the set if they are present.
Removes the elements in the specified set from the original set if they are present.
Retains only the elements in this set that are contained in the specified list.
Retains only the elements in the original set that are contained in the specified set.
Returns the number of elements in the set
We cannot use list and set interchangeably unless it is very required, let's see when to use list and when to use set.
Maps are not part of collection but built based on the collection concepts
Map is nothing but a key value pair mappings, every in the map a has a value and every value has a key.
Map keys follows Set interface and allows only unique values, Map Values are following List interface and allows duplicates
It is similar to the attendance system, the roll number is Keys, and names are Values. Roll Number is unique but the names could be duplicates.
We will discuss only important methods present in the Maps.
It removes all the key and value pairs from the specified Map.
It returns a copy of all the mappings of a map and used for cloning them into another map.
It is a boolean function which returns true or false based on whether the specified key is found in the map.
Similar to containsKey() method, however it looks for the specified value instead of key.
It returns the value for the specified key.
It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.
It returns the Set of the keys fetched from the map.
Inserts key value mapping into the map. Used in the above example.
Returns the size of the map – Number of key-value mappings.
It returns a collection of values of map.
It removes the key-value pair for the specified key. Used in the above example.
Copies all the elements of a map to the another specified map.
In my Way : Collection is like road, any vehicle can go on the road. Consider that it is peak time and you have heavy traffic(2, 4, 6 wheelers) on the road, now you feel like you want to make all the vehicles to into two wheelers(I'm assuming that you are not having super powers), is it possible ? No. If you force to convert, you may have
Consider that there is road which allows only two wheelers, now it has traffic, will you able convert them into two wheelers ?, Yes, because we allowed only two wheelers on the road.
Coming to the Generic, Generic is nothing but the road which accepts everything, Generic provides way to make it accept only one kind of value.
In above examples you might have noticed that few Data types are inside
Below code shows that the ArrayList accepts only the type of String values into the List.
Common syntax:
List< Generic > = new ArrayList();
ArrayList <String;> products = new ArrayList();
When we didnot mention any generic type then collection will accept everything but if we mention some type then collection will accept only that types of data.
Consider in a scenario you want to store boolean values in a list without specifying the generic type, so you got 8 values as boolean and one value as float, and another values as int.
Do you think, we can convert int to boolan, or float to boolean ?, No, you cannot convert.
This is what happens when you donot specify any generic type in the collection and this throws
But if we make a list to accept only boolean values while accepting if it identifies the int value then it will not only reject but also gives you an error during compile time itself.
Have you ever tried to work with findElements() method in selenium, if yes then what is return type of the findElements method.
findElements in selenium returns List<WebElement;>, so now got to know that with/without knowing you have worked with generics.
List<WebElement;> elements = driver.findElements(By.tagName("button"));
I hope you have worked on handling multiple windows, when we have multiple windows we would be using
Generics add re-usability by enabling you to define a class or interface without specifying fixed parameter data types.
In practical application this feature enables the creation of some very flexible code. For example, you need to write an interface that takes both integer and string values for the same parameter. How do you handle it?
You might write a single interface with weak data typing, but this creates its own issues and is against best practices.
You could write two versions of the interface. This allows strong data types, but creates additional code to be maintained.
Generics allow you to combine the best of both by enabling a single definition of the interface that maintains strong typing.
The desired data type (string or int) is defined at the time of use. This also can help with code optimization.
This flexible yet strong data typing allows you to avoid heavy usage of casting and other processing intensive method calls.
Often you will want to traverse through the elements of a collection, say to display each element.
The better way is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to traverse through the elements, add or remove elements. This is unidirectional. ListIterator is Bi-directional in traversing.
Iterator cursor maintains its position moved by the previous operation unless disturbed
So when we move the cursor to end in last operation then it stays there only unless we change it, in below example
import java.util.ArrayList;
import java.util.Iterator;
public class SampleIterator {
public static void main(String args[]){
ArrayList products = new ArrayList();
products.add("Chercher tech");
products.add("Google");
products.add("Bing");
Iterator it = products.iterator();
while(it.hasNext()) {
String obj = it.next();
System.out.println("Value : " +obj);
}
}
}
An iterator for lists that allows one to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.
The iterator position of a ListIterator is never placed at an element rather it is placed between two elements in a list. Because of this List Iterator has capability to make it traverse in both directions, i.e., forward and backward.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import org.testng.annotations.Test;
public class SampleListIterator {
@Test
public void test(){
ArrayList fruits = new ArrayList();
fruits.add("Chercher tech");
fruits.add("Google");
fruits.add("Bing");
ListIterator itList = fruits.listIterator();
while(itList.hasNext()) {
String obj = itList.next();
System.out.println("Value : " +obj);
}
System.out.println("*********Reverse the Iteration*********");
while(itList.hasPrevious()) {
String objPrev = itList.previous();
System.out.println("Value : " +objPrev);
}
}
}
Output of the List Iterator:
Value : Chercher tech
Value : Google
Value : Bing
*********Reverse the Iteration*********
Value : Bing
Value : Google
Value : Chercher tech
Below are the few difference between the Collection(framework), Collections class.
There are so many difference but I am highlighting whatever i know, so there is chance that more than these differences to be present between them.
Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know.
Knowledge is the only thing that doubles when you spend it.
I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation
Hello, This is very good tutorial website and simple language but somewhere spelling mistake that why i am having problem to understand. thank you
Hi Rahul, Thanks for feedback, I have removed spelling mistakes from this page. DO tell us if you find mistakes any where, (there are lot of it)