JAVA

Java Collections class

Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class.

Method

Description

static <T> boolean addAll(Collection<? super T> c, T... elements)

It is used to add all of the specified elements to the specified collection.

static <T> Queue<T> asLifoQueue(Deque<T> deque)

It is used to return a view of a Deque as a Last-In-First-Out (LIFO) Queue.

static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T< c)

It is used to search the specified list for the specified object using the binary search algorithm.

static <E> List<E> checkedList(List<E> list, Class<E> type)

It is used to return a dynamically typesafe view of the specified list.

static <E> Set<E> checkedSet(Set<E> s, Class<E> type)

It is used to return a dynamically typesafe view of the specified set.

static <E> SortedSet<E>checkedSortedSet(SortedSet<E> s, Class<E> type)

It is used to return a dynamically typesafe view of the specified sorted set

static void reverse(List<?> list)

It is used to reverse the order of the elements in the specified list.

Collections example program

import java.util.*;

public class CollectionsExample{

           public static void main(String[] args) {

List<Integer> list=new ArrayList<Integer>();

list.add(46);

list.add(67);

list.add(24);

list.add(16);

list.add(8);

list.add(12);

System.out.println("Value of maximum element from the collection:"+Collections.max(list));

}

}


OUTPUT:

value of maximum element from the collection: 67


 

 

Java Comparable interface

Java Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only one method named compareTo(Object). It provide single sorting sequence only i.e. you can sort the elements on based on single data member only. For example it may be rollno, name, age or anything else.

compareTo(Object obj) method

public int compareTo(Object obj): is used to compare the current object with the specified object.

We can sort the elements of:

1.    String objects

2.    Wrapper class objects

3.    User-defined class objects

Java Comparator interface

Java Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data member, for example rollno, name, age or anything else.

compare() method

public int compare(Object obj1,Object obj2): compares the first object with second object.