Hierarchy in Collection Framework – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Wed, 05 Jul 2023 04:19:54 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Hierarchy in Collection Framework – Programmerbay https://programmerbay.com 32 32 ArrayList Class in Java With Program Example https://programmerbay.com/arraylist-class-in-java-with-program-example/ https://programmerbay.com/arraylist-class-in-java-with-program-example/#respond Wed, 05 Jul 2023 04:19:54 +0000 https://programmerbay.com/?p=9336 Arraylist is a child class of AbstractList and implements List interface. It represents dynamic array that can grow or shrink as needed. In case of standard array, one must know the number of elements about to store in advance. In other words, a standard array is fixed in size and its size can’t be changed after its initialisation. To overcome this problem, collection framework provides ArrayList.

Point to Remember

1. It is a growable array
2. It allows duplicate elements
3. It preserves insertion order
4. It can store different types of elements
5. It can have null values
6. It resides in java.util package
7. By default, it is non synchronized class
8. It is not thread safe
9. It uses zero-based index to access, add, delete and update an element
10. If frequent operation is retrieve operation, then arrayList is best choice.
11. If insertion and removal in middle is the operation then arrayList is worst choice.
12. It doesn’t work with primitive types

Constructors in ArrayList

There are three constructors associated with ArrayList to create its objects.

1. new ArrayList() : A default constructor that takes no input and creates an empty list with default capacity. By default, it intializes with capacity of 10, meaning, it can hold 10 elements.

However,when an eleventh element is inserted in a list. JVM automatically generates a larger list with greater capacity and copies the element from old one to new one. Further, it changes reference variable to point to the new list, making old list eligible for garbage collection.

How to calculate capacity of ArrayList?

This is the formula used to calculate new capacity of an arrayList
new Capacity = (current capacity * 3/2)+1

ArrayList<ObjType> arr = new ArrayList<>();

2. new ArrayList ( int capacity) : A parameterised constructor that takes capacity as an input and creates an empty list with provided initial capacity.

ArrayList<ObjType> arr = new ArrayList<>(capacity);

3. new ArrayList (Collection c) : The constructor takes collection object as an input and creates an equivalent list from the given collection

ArrayList<ObjType> arr = new ArrayList<>(c);

The purpose of collection is to hold a group of data that can be transferred from one place to another place, it can be over the network or data sources. In order to provide this support, it is compulsory to implement serializable interface. Therefore, all the collection implementation classes implements serializable class.

Further, Arraylist and Vector implements RandomAccess interface that signifies accessing any element using index which takes same time.
RandomAccess interface is present in java.util packages and doesn’t consist any method. It’s a marker interface.

How to define an ArrayList?

ArrayList implements List interface and is a generic class with below definition:

ArrayList<ObjType> list = new ArrayList<>();
  • ObjType is any non-primitve dataType
  • new keyword is used to allocate memory and create an object.
  • ArrayList<>() is default constructor

 

Methods in Java ArrayList

MethodExplanation
add(T obj)It inserts an element to the end and returns true if the element is added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatiable collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear() It removes or truncates all the elements from the given list
contains(Object obj) It returns true if the given object is present within the list
containsAll(Collection obj) It returns true if all the elements in the given collection are present in the list
equal(Object obj) It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It check whether a list contains any element or not.
iterator() It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator() It returns object of ListIterator
listIterator(int indx) It returns listIterator object with the starting point specified with indx
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj) It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator
spliIterator()It returns SplitIterator object
subList(int from, int to) It returns sublist that falls between fromIndx and toIndex
toArray() It converts and returns an array corresponding to the given list
MethodsExplanation
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Operations in ArrayList

There are various operations can be performed on a ArrayList. These are

1. Element addition
2. Element updation
3. Element deletion
4. Element traversal
5. Element access
6. Element sorting

1. Adding an element in an Array

ArrayList provides implementation to add() method inherited from List interface. There are overloaded versions of add() method.

add(obj) : It appends an element to the end of a list
add(indx,obj) : It adds an element at the given position in a list

Below is the simple java program to add an element in an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list content :: "+ integerArrayList);
}
}

Output:

The list content :: [5, 10, 1]

2. Updating or replacing an element in an ArrayList

ArrayList provides set() method to set or replace an element at given position. The method takes index and the element as an input to replace and uses the index to locate the position and replaces the element with new value.

set(indx, obj) : It replaces an element at the given position with the new element.

Below is the simple java program to replace or update an element in an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list :: "+ integerArrayList);

integerArrayList.set(1,100); // replacing element (10) at index 1 with 100

System.out.println(integerArrayList);
}
}

Output:

The list content :: [5, 10, 1]

3. Deleting an element from an ArrayList

remove() method is used to delete an element from a list. It has multiple overloaded versions. These are :

remove(obj) : It deletes very first occurrence of the matched object in a list.
remove(int indx): It deletes an element located at a given position or index

Below is the simple Java program to delete or remove an element from an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("The list :: "+ integerArrayList);

integerArrayList.remove(1); // removing element (10) at index 1

System.out.println(integerArrayList);
}
}

Output:

The list :: [5, 10, 1]
[5, 1]

4. Iterating over elements of an ArrayList

All the collection framework classes indirectly implements Iterable interface. The iterable interface provides various methods which empowers iterating ArrayList. These are :

Iterator() : It returns Iterator Object. It provides a way to iterate over a list
forEach(Consumer action) : It iterates and performs action over each element until all the element are processed.

Apart from this, for-each or advance for loop can be used to iterate through elements of a list

Below is the simple Java program to iterate through an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);

System.out.println(" Iterating through iterator :: ");
Iterator itr = integerArrayList.iterator(); // getting iterator object from arraylist instance
while(itr.hasNext()) // while the list has the content, do
{
System.out.println(itr.next()); // returns the current element and moves the iteration state to next element
}

System.out.println(" Iterating through forEach :: ");
integerArrayList.forEach(System.out::println); // Java 8 forEach with lambda exp

System.out.println(" Iterating through for-each :: ");

for (Integer val:
integerArrayList) {
System.out.println(val);
}

}
}

Output:

Iterating through iterator ::
5
10
1
Iterating through forEach ::
5
10
1
Iterating through for-each ::
5
10
1

5. Fetching an element from an ArrayList

ArrayList uses zero-based index in order to access an element. It provides a method named get() that takes index as an input and returns the element at that position

get(indx) : returns an element at the given position

Below is the simple Java program to get or fetch an element from an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);

System.out.println("Fetching element at index 2 :: "+ integerArrayList.get(2));

}
}

Output:

Fetching element at index 2 :: 1

7. Sorting elements in an ArrayList

Sort() method is used to sort a list in ArrayList. It takes comparator as an input and applies on elements to achieve sorting.

sort(Comparator c): sorts elements in a list

Below is the simple java program to sort an ArrayList

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<>();
integerArrayList.add(5);
integerArrayList.add(10);
integerArrayList.add(1);
System.out.println("before sorting :: "+integerArrayList);

integerArrayList.sort(Comparator.comparingInt(Integer::intValue));
System.out.println("after sorting :: "+integerArrayList);

}
}

Output:

before sorting :: [5, 10, 1]
after sorting :: [1, 5, 10]

How to get length or size of an ArrayList?

size() method is used to get length or size of an array in arrayList.

size() : returns length of a list
integerArrayList.size();

 

]]>
https://programmerbay.com/arraylist-class-in-java-with-program-example/feed/ 0
List Interface in Java With Program Example https://programmerbay.com/list-interface-in-java-with-program-example/ https://programmerbay.com/list-interface-in-java-with-program-example/#respond Tue, 04 Jul 2023 13:54:56 +0000 https://programmerbay.com/?p=9331 List interface inherits Collection interface that provides behaviour to store a group of individual objects. It represents group of individual objects as single entity where duplicates are permitted and elements are ordered in the same manner in which they are inserted. It resides within java.util packages.

Screenshot from 2023 07 04 19 23 17

It defines listIterator() method which returns ListIterator object which empowers the implementing classes to able to traverse their collection objects in both directions, forward and backward.

ArrayList,LinkedList, Stack and Vector are the implementing classes of List interface. Vector class is the legacy class in the List hierarchy.

It allows index based element access and also can be used to insert an element using its position in the given list using zero based index.
A list can contain duplicate elements. It defines its own methods that is specifically made for List implementing classes.

Important Notes

1. It is an ordered collection, meaning, elements are stored the manner in which they are inserted. Therefore, it preserves the insertion order.
2. It uses zero based index in order to access, insert and search element in the list
3. It allows duplicate elements
4. It accepts and stores elements of different types

Method of List Interface

Since, it is child interface of Collection, therefore, it has access all of its method. Apart from this, List interface defines its own methods. The methods and explanations are given below

MethodsExplanation
add(T obj)It inserts an element to the end and returns true if it's added successfully
add(int indx, T obj)It inserts the given element at the specified index of the list
addAll(Collection c)It adds entire compatible collection objects to the end of the list
addAll(int indx, Collection c)It inserts all the compatiable collection objects at the given index in the list
clear()It removes or truncates all the elements from the given list
contains(Object obj)It returns true if the given object is present within the list
containsAll(Collection obj)It returns true if all the elements in the given collection are present in the list
equals(Object obj)It returns true if the given object is equivalent to the list
hashCode()It returns hashcode of a list
indexOf(Object c)It returns the index of the given object which matches first, oterwise -1 is returned
isEmpty()It checks whether a list contains any element or not.
iterator()It returns iterator object for a list
lastIndexOf(Object obj)It returns index of the given object which match first from the last, otherwise, -1 is returned
listIterator()It returns object of ListIterator
listIterator(int indx)It returns listIterator object with the starting point specified with indx.
remove(int index)It removes an element from the specified position and returns the removed object from the list
remove(Object obj)It removes very first occurrence of the given object from the list.
removeAll(Collection obj)It removes all the elements that are present in the given collection from the list
replaceAll(UnaryOperator operator)It replaces all the elements by performing the given operator to them in the list
retainAll(Collection c)It retains all the elements that matches in the given list and removes all others from the list
set(int indx, T obj)It replaces the given object at specified position and returns the replaced object.
size()It returns number of elements present in the list
sort(Comparator c)It sorts the list based on given order specified in the comparator.
spliIterator()It returns SplitIterator object
subList(int from, int to)It returns sublist that falls between fromIndx and toIndex
toArray()t converts and returns an array corresponding to the given list

Classes that implements List interface

These are the following classes that implements List Interface
1. ArrayList
2. LinkedList
3. Vector
4. Stack

ArrayList

ArrayList resembles dynamic array behaviour in Collection framework. It provides a way to overcomes from fixed size problem of standard arrays. Apart from that, it supports several predefined methods and also uses zero-based index to access, remove or retrieve an object from a list. In other words, it is an array list with growable size functionality.

Vector

Vector is a legacy class in Collection framework. Its underlying data structure is also growable array. It uses zero based index in order to operate on objects and its size can be grow or shrink on runtime based on objects in the list.

Stack

Stack is a child class of Vector. As name suggest, its behaviour resembles Stack data structure. It follows basic principle of Stack which is last in first out. Apart from this, it offers various inbuilt methods to perform basic Stack operation, involving, push(), pop() and peak().

LinkedList

LinkedList implements Linked list data structure in Collection framework. It uses addresses to locate and form a sequence of elements that are stored at different location. In this, each element is termed as node which keep data and address of next or previous element.
It can be considered where insertion and deletion, are frequent operation.

How to declare and define a List?

A List interface only declares behaviour, but not implementation. It is not possible to create its object. Therefore, a List can only hold reference of its implementing classes object. Since, it use Generics concept, therefore, it is controllable to define which type of object a list can hold.

Syntax:

List<Obj> listRef = new ArrayList<>();
List<Obj> listRef = new Stack<>();
List<Obj> listRef = new Vector<>();
List<Obj> listRef = new LinkedList<>();

Obj represents the Type of object the list can hold

Below is the simple Java program to declare a list.

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
System.out.println(list); // printing the output
}
}

Output:

[Viewer]

 

Basic Operations that List Interface provides

1. Adding elements to the List

List provides add() and addAll() methods in order to add elements in the list.

Syntax:

add(Object obj) : It adds element to the end of the list
add(int indx,Object obj) : It adds element on specified position
addAll(Collection c) : It adds another list at the end of the list

Below is the simple Java program to add elements in the list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
list.add("Viewer2"); // added single element in the list
System.out.println(list); // printing the output

list.add(1,"inserted"); // added element at first position
System.out.println(list);

List<String> anotherList = new ArrayList<>();
anotherList.add("another list content1") ;
anotherList.add("another list content2") ;

list.addAll(anotherList); // adding all elements of another list
System.out.println(list);

}
}

Output:

[Viewer, Viewer2]
[Viewer, inserted, Viewer2]
[Viewer, inserted, Viewer2, another list content1, another list content2]

2. Updating elements to the List

List provides set() and replace() method to update the elements of a list.

set(int index, Obj element) : It updates or replaces element in the list at the given position
replaceAll(UniaryOperator op) : It replaces all the elements in the list.

Below is the simple java program to replace elements in the list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added single element in the list
list.add("Viewer2"); // added single element in the list
System.out.println(list); // printing the output

System.out.println("After replace -----------");
list.set(1, "Kui"); // replaced the viewer2 value with Kui in the list
System.out.println(list);

System.out.println("After replace All -----------");
list.replaceAll(String::toUpperCase); // a lambda expression (Java 8 feature), that denotes replaces all the elements with its Uppercase version
System.out.println(list); // replaced the viewer2 value with Kui in the list

}
}

Output:

[Viewer, Viewer2]
After replace -----------
[Viewer, Kui]
After replace All -----------
[VIEWER, KUI]

3. Deleting elements to the List

List interface provides remove() and removeAll method to delete elements from the list.

remove(int indx) : It deletes elements at the given position
remove(Object obj) : It deletes very first occurrence of the given object
removeAll(Collection c) : It deletes all the eleemnts that matches with the given collection object

Below is the simple Java program to delete or remove elements from a list

Program:

import java.util.ArrayList;
import java.util.List;

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Viewer"); // added element in the list
list.add("Viewer2");
list.add("Viewer3");
list.add("Viewer4");
list.add("Viewer3");


System.out.println(list); // printing the output

System.out.println("After deleting element at 1st index -----------");
list.remove(1); // removed the viewer2 value
System.out.println(list);

System.out.println("After deleting element at Viewer3 object (very first match only)-----------");
list.remove("Viewer3"); // removed the viewer3 value,only very first occurrence
System.out.println(list);

System.out.println("After deleting elements defined in another list -----------");
List<String> deleteList = new ArrayList<>();
deleteList.add("Viewer4");
list.removeAll(deleteList); // removed the viewer4 value
System.out.println(list);
}
}

Output:

[Viewer, Viewer2, Viewer3, Viewer4, Viewer3]
After deleting element at 1st index -----------
[Viewer, Viewer3, Viewer4, Viewer3]
After deleting element at Viewer3 object (very first match only)-----------
[Viewer, Viewer4, Viewer3]
After deleting elements defined in another list -----------
[Viewer, Viewer3]

4. Sorting elements in the List

List provides sort() method to sort list

sort (Comparator c) : It sorts list based on given comparator

Below is the simple Java program to sort list

Program:

public class ListDeclarationExample {

public static void main(String[] args) {
List<String> list = new ArrayList<>(); // list is a reference variable that can hold object of List Type or its implementing classes
list.add("Sandeep"); // added element in the list
list.add("Sachin");
list.add("Jay");
list.add("Shiva");
list.add("Kui");

System.out.println("Before sorting based on the string length or size"); // printing the output
System.out.println(list); // printing the output

System.out.println("After sorting based on the string length or size"); // printing the output

list.sort(Comparator.comparingInt(String::length)); // It would sort the list based on the size or length of a string in increasing order

System.out.println(list); // printing the output


}
}

Output:

Before sorting based on the string length or size
[Sandeep, Sachin, Jay, Shiva, Kui]
After sorting based on the string length or size
[Jay, Kui, Shiva, Sachin, Sandeep]

5. Iterating over elements in List

List indirectly extends Iterable interface that provides method to iterate through collection objects. iterator() method and forEach() methods are one of methods.

Also, using advance for-each, one can iterate through a list.

Below is the simple Java Program to iterate through a List

Program:

public class ListDeclarationExample {

    public static void main(String[] args) {
        ArrayList<Integer> integerArrayList = new ArrayList<>();
        integerArrayList.add(5);
        integerArrayList.add(10);
        integerArrayList.add(1);

        System.out.println(" Iterating through iterator :: ");
        Iterator itr = integerArrayList.iterator();  // getting iterator object from arraylist instance
        while(itr.hasNext())    // while the list has the content, do
        {
            System.out.println(itr.next()); // returns the current element and moves the iteration state to next element
        }

        System.out.println(" Iterating through forEach :: ");
        integerArrayList.forEach(System.out::println);  // Java 8 forEach with lambda exp
    }
}

Output:

 Iterating through iterator :: 
5
10
1
 Iterating through forEach :: 
5
10
1

 

]]>
https://programmerbay.com/list-interface-in-java-with-program-example/feed/ 0
Collections in Java With Program Examples https://programmerbay.com/collections-in-java-with-program-examples/ https://programmerbay.com/collections-in-java-with-program-examples/#respond Tue, 04 Jul 2023 12:18:29 +0000 https://programmerbay.com/?p=9306 A collection can be defined as a group of objects (elements) represented as a single entity.
Collections in Java can be viewed as Collection Framework which is the most powerful feature. Collection Framework represents a hierarchy of interfaces and classes that is used to manage, handle and store groups of objects efficiently. It resides within java.util package. It wasn’t initially part of Java and was added later in J2SE 1.2.

Prior to Collection Framework, the legacy classes such as Dictionary, Vector, Stack, and Properties present in the framework, were used to store and manipulate groups of objects.

Java Collection Framework

Collection Framework is a hierarchy of several interfaces and classes that are used to represent a collection. In other words, It can be viewed as an architecture for handling and manipulating collections efficiently.
It comprises of following :
  • Interfaces
  • Classes
  • Algorithms
It works with a reference type only, not with a primitive type.
After the introduction of Generics, the collection framework became more powerful.

What are the advantages of the Collection Framework in Java?

  • Increase in Performance: It provides support for high-performance data structures and algorithms such as dynamic arrays, linked lists, hash tables and trees which are highly efficient.
  • Interoperability: It provides unified behaviour among collections as a result they can operate with one another
  • Easy to Adopt and Use: It represents the hierarchy of interfaces and their implementation classes which can either be used directly or can be used to form a user-defined collection.
  • Standard Array integration: It provides array integration into the collection framework.
  • Reduces Programming Efforts: Each collection class is built upon some underlying data structure based on which it manipulates and works with objects. As a result, it provides several predefined methods for data searching, sorting, insertion, manipulation, and deletion which can be used as-is.

 

Hierarchy of Collection framework in Java

The below hierarchy resembles all the classes and interfaces that formulates Collection Framework architecture.  These classes and interfaces reside within java.util package.

Untitled Diagram
Hierarchy of Collection Framework
Collection Framework
Map Hierarchy of Collection Framework

9 Key interfaces in Collection Framework

1. Collection Interface : It consists all the common methods that can be used by any collection object. It specifies behaviour specifically for List and Set. Therefore, it builds foundation for Collection Framework on which all collections work. It can be considered as root interface of collection framework. No class implements collection interface directly.

It provides core methods such as add(), remove(), isEmpty()  and more, to work with collection objects.

Syntax: 

public interface Collection<T> extends Iterable<T> {
}

 

2. List Interface :

List Interface directly extends Collection. It represents ordered collection or sequence of objects. It specifies a type of data structure where duplicates are allowed and insertion order preserved. ArrayList, LinkedList, Vector and Stack are its implementing classes. Further, It supports implementation for legacy classes that are Vector & Stack which was introduced in Java 1.0 version.

Syntax :

public interface List<T> extends Collection<T> {}

3. Set Interface : A Set interface specifies a type of collection where duplicates are not allowed and insertion order is not preserved. It also extends collection interface. It allows null values and can store elements of different types. HashSet, LinkedHashSet, and TreeSet are the implementing classes of Set.

Syntax : 

public interface Set<T> extends Collection<T> {}

4. SortedSet Interface : It is a child interface of Set. It doesn’t allow duplicates and represents group of elements in some sorting order. It accepts elements of same type that can be ordered in natural sorting order or user-defined order using Comparator.

Syntax:

public interface SortedSet<T> extends Set<T>

 

5. NavigivableSet Interface : It extends SortedSet. It defines various methods to traverse or navigate from one element to other in the given collection. TreeSet is the implementing class of NavigavbleSet.

Syntax:

public interface NavigableSet<T> extends SortedSet<T>{}

6. Queue Interface: It is a child interface of Collection. It represents a group of elements prior to processing or about to be processed in FIFO manner. In other words, it holds elements in a manner of first in first out order before processing. LinkedBlockingQueue and PriorityBlockingQueue are the classes that implements Queue interface.

Syntax:

public interface Queue<T> extends Collection<T>{}

7. Map Interface: 

Map interface represents a group of objects as key value pair, not a group of individual objects. Therefore, Map and Collection interface are two different concepts, as a result, a separate hierarchy is followed in this case for collection Framework. HashMap,linkedHashMap, WeakHashMap, and Hashtable are the implementation class of Map interface.

Syntax:

public interface Map<K,V>

8. SortedMap Interface : It is a child interface of Map. It represents a group of elements in key value pairs where they are stored in some key sorting order.

Syntax:

public interface SortedMap<K,V> extends Map<K,V>{}

9. NavigableMap Interface: It is child interface of SortedMap.Simmilar to NavigableSet, it defines several methods for navigation or traversing purpose. TreeMap is the implementation class of this interface.

Syntax:

public interface NavigableMap<K,V> extends SortedMap<K,V>

Frequently Asked Questions:

1.What is Collection Framework in Java?

Collection Framework is an hierarchy of interfaces and classes to store and manipulate a group of elements efficiently.

2. Why we use Collection Framework in Java?

It provides several high performance classes that are built upon some underlying data structures, offering predefined methods which reduces programming efforts. Therefore, it is used to store and manipulate a group for elements efficiently.

3. Why we need Collection Framework in Java?

There are several limitations of arrays.
An array is not growable in nature ( one needs to define the size of an array at the time of decleration ) therefore, it’s fixed in size and can’t be increased or decreased as per requirement..
Secondly, it supports only elements of same types, as a result, it limits the store elements to the same type.
Lastly, it is not build upon some standard data structure, due to which, there are no predefined methods for data manipulation.
To overcome limitations of Arrays, collection is needed.

4. When was Collection Framework introduced in Java?
It was introduced in JDK 1.2 version.
5. Which package contain all the collection classes ?
java.util package contains all the collection classes.
6. How to import collections in Java?
One can import collection interface or classes by using import java.util.* statement.
7. Which collection contains ordered collection of elements?
List contains ordered collection of elements. ArrayList, Vector and LinkedList are the classes that store ordered collection objects. Ordered collection means sequence, meaning elements gets stored in the same manner in which they are stored.

]]>
https://programmerbay.com/collections-in-java-with-program-examples/feed/ 0