Automation Using Selenium Webdriver

Monday, 23 January 2017

Difference between Collections and Collection in java with example program

Difference between Collections and Collection in java with example program

Famous java interview question: difference between collections and collection in java
Major difference between Collection and Collections is Collection is an interface and Collections is a class.
Both are belongs to java.util package
Collection is base interface for list set and queue.
Collections is a class and it is called utility class.
Collections utility class contains some predefined methods so that we can use while working with
Collection type of classes(treeset, arraylist, linkedlist etc.)
Collection is base interface for List , Set and Queue.


Collection vs Collections

public interface Collection<E>
extends Iterable<E>


public class Collections
extends Object

Collections utility class contains static utility methods so that we can use those methods by using
class name without creating object of Collections class object
Lest see some methods of Collections class.


addAll: public static <T> boolean addAll(Collection<? super T> c,T... elements)
reverseOrder: public static <T> Comparator<T> reverseOrder()
shuffle: public static void shuffle(List<?> list)
sort:public static <T extends Comparable<? super T>> void sort(List<T> list)
How to Relate Collection and Collections
ArrayList is a Collection type of class means it is implementing Collection interface internally
Now lets see a java example program to sort ArrayList of elements using Collections.sort() method.

public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable


1.Basic Java example program to sort arraylist of integers using Collections.sort() method

package com.javasortarraylistofobjects;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class SortArrayListExample{

public static void main(String[] args) {

//create an ArrayList object
 ArrayList<Integer> arrayList = new ArrayList<Integer>();
     
 //Add elements to Arraylist
arrayList.add(10);
arrayList.add(7);
arrayList.add(11);
arrayList.add(4);
arrayList.add(9);
arrayList.add(6);
arrayList.add(2);
arrayList.add(8);
arrayList.add(5);
arrayList.add(1);
     
     
 System.out.println("Before sorting ArrayList ...");
 Iterator itr=arrayList.iterator();
     
while (itr.hasNext()) {

System.out.println(itr.next());
   
}

     
 /*
 To sort an ArrayList object, use Collection.sort method. This is a
  static method. It sorts an ArrayList object's elements into ascending order.
*/
  Collections.sort(arrayList);
   
  System.out.println("After sorting ArrayList ...");
     
 
     
Iterator itr1=arrayList.iterator();
     
while (itr1.hasNext()) {

System.out.println(itr1.next());
         
}
 

}
}



Output:

Before sorting ArrayList ...
10
7
11
4
9
6
2
8
5
1
After sorting ArrayList ...
1
2
4
5
6
7
8
9
10
11