Collection Framework
Collection framework was not part of original Java release. Collections was added to J2SE 1.2. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects. Collection framework provides many important classes and interfaces to collect and organize group of alike objects.Important Interfaces of Collection API
Interface | Description |
---|---|
Collection | Enables you to work with groups of object; it is at the top of collection hierarchy |
Deque | Extends queue to handle double ended queue. |
List | Extends collection to handle sequences list of object. |
Queue | Extends collection to handle special kind of list in which element are removed only from the head. |
Set | Extends collection to handle sets, which must contain unique element. |
SortedSet | Extends sets to handle sorted set. |
Why Collections were made Generic ?
Generics added type safety to Collection framework. Earlier collections stored Object class references. Which means any collection could store any type of object. Hence there were chances of storing incompatible types in a collection, which could result in run time mismatch. Hence Generics was introduced, now you can explicitly state the type of object being stored.Collections and Autoboxing
We have studied that Autoboxing converts primitive types into Wrapper class Objects. As collections doesn't store primitive data types(stores only refrences), hence Autoboxing facilitates the storing of primitive data types in collection by boxing it into its wrapper type.Most Commonly thrown Exceptions in Collection Framework
Exception Name | Description |
---|---|
UnSupportedOperationException | occurs if a Collection cannot be modified |
ClassCastException | occurs when one object is incompatible with another |
NullPointerException | occurs when you try to store null object in Collection |
IllegalArgumentException | thrown if an invalid argument is used |
IllegalStateException | thrown if you try to add an element to an already full Collection |
Interfaces of Collection Framework
The collection framework has a lot of Interfaces, setting the fundamental nature of various collection classes. Lets study the most important Interfaces in the collection framework.The Collection Interface
- It is at the top of collection heirarchy and must be implemented by any class that defines a collection. Its general declaration is,
- Following are some of the commonly used methods in this interface.
interface Collection < E >
Methods | Description |
---|---|
add( E obj ) | Used to add objects to a collection. Doesn't add duplicate elements to the collection. |
addAll( Collection C ) | Add all elements of collection C to the invoking collection |
remove( Object obj ) | To remove an object from collection |
removeAll( Collection C ) | Removes all element of collection C from the invoking collection |
contains( Object obj ) | To determine whether an object is present in collection or not |
isEmpty() | Returns true if collection is empty, else returns false |
size() | returns number of elements present in collection |
The List Interface
- It extends the Collection Interface, and defines storage as sequence of elements. Following is its general declaration,
- Allows random access and insertion, based on position.
- It allows Duplicate elements.
- Apart from methods of Collection Interface, it adds following methods of its own.
interface List < E >
Methods | Description |
---|---|
get( int index ) | Returns object stored at the specified index |
set( int index, E obj) | Stores object at the specified index in the calling collection |
indexOf( Object obj ) | Returns index of first occurence of obj in the collection |
lastIndexOf( Object obj ) | Returns index of last occurence of obj in the collection |
subList( int start, int end ) | Returns a list containing elements between start and end index in the collection |
The Set Interface
- This interface defines a Set. It extends Collection interface and doesn't allow insertion of duplicate elements. It's general declaration is,
- It doesn't define any method of its own. It has two sub interfaces, SortedSet and NavigableSet.
- SortedSet interface extends Set interface and arranges added elements in an ascending order.
- NavigabeSet interface extends SortedSet interface, and allows retrieval of elements based on the closest match to a given value or values.
interface Set < E >
The Queue Interface
- It extends collection interface and defines behaviour of queue, that is first-in, first-out. It's general declaration is,
- There are couple of new and interestin methods added by this interface. Some of them are mentioned in below table.
interface Queue < E >
Methods | Description |
---|---|
poll() | removes element at the head of the queue and returns null if queue is empty |
remove() | removes element at the head of the queue and throws NoSuchElementException if queue is empty |
peek() | returns the element at the head of the queue without removing it. Returns null if queue is empty |
element() | same as peek(), but throws NoSuchElementException if queue is empty |
offer( E obj ) | Adds object to queue. |
The Dequeue Interface
- It extends Queue interface and declares behaviour of a double-ended queue. Its general declaration is,
- Double ended queues can function as simple queues as well as like standard Stacks.
interface Dequeue < E >
The Collection classes
Java provides a set of Collection classes that implements Collection interface. Some of these classes provide full implementations that can be used as it is and other abstract classes provides skeletal implementations that can be used as starting points for creating concrete collections.ArrayList class
- ArrayList class extends AbstractList class and implements the List interface.
- ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors.
- ArrayLists are created with an initial size, when this size is exceeded, it gets enlarged automatically.
- It can contain Duplicate elements and maintains the insertion order.
- ArrayLists are not synchronized.
ArrayList() ArrayList( Collection C ) ArrayList( int capacity )
Example of ArrayList
import java.util.* class Test { public static void main(String[] args) { ArrayList< String> al = new ArrayList< String>(); al.add("ab"); al.add("bc"); al.add("cd"); system.out.println(al); } }
Output : [ab,bc,cd]
Getting Array from an ArrayList
toArray()
method is used to get an araay containing all
the contents of the list. Following are the reasons why you must obtain
array from your ArrayList whenever required.- To obtain faster processing.
- To pass array to methods who do not accept Collectionn as arguments.
- To integrate and use collections with legacy code.
Storing User-Defined classes
In the above example we are storing only string object in ArrayList collection. But You can store any type of object, including object of class that you create in Collection classes.Example of storing User-Defined object
Contact classclass Contact { String first_name; String last_name; String phone_no; public Contact(String fn,String ln,String pn) { first_name = fn; last_name = ln; phone_no = pn; } public String toString() { return first_name+" "+last_name+"("+phone_no+")"; } }Storing Contact class
public class PhoneBook { public static void main(String[] args) { Contact c1 = new Contact("Ricky", "Pointing","999100091"); Contact c2 = new Contact("David", "Beckham","998392819"); Contact c3 = new Contact("Virat", "Kohli","998131319"); ArrayList< Contact> al = new ArrayList< Contact>(); al.add(c1); al.add(c2); al.add(c3); System.out.println(al); } }Output
[Ricky Pointing(999100091), David Beckham(998392819), Virat Kohli(998131319)]
LinkedList class
- LinkedList class extends AbstractSequentialList and implements List,Deque and Queue inteface.
- It can be used as List, stack or Queue as it implements all the related interfaces.
- It can contain duplicate elements and is not synchronized.
Example of LinkedList class
import java.util.* ; class Test { public static void main(String[] args) { LinkedList< String> ll = new LinkedList< String>(); ll.add("a"); ll.add("b"); ll.add("c"); ll.addLast("z"); ll.addFirst("A"); System.out.println(ll); } }
Output : [A, a, b,c, z]
HashSet class
- HashSet extends AbstractSet class and implements the Set interface.
- It creates a collection that uses hash table for storage.
- HashSet does not maintain any order of elements.
Example of HashSet class
import java.util.*; class HashSetDemo { public static void main(String args[]) { HashSet< String> hs = new HashSet< String>(); hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } }
Output: [D, E, F, A, B, C]
LinkedHashSet Class
- LinkedHashSet class extends HashSet class
- LinkedHashSet maintains a linked list of entries in the set.
- LinkedHashSet stores elements in the order in which elements are inserted.
Example of LinkedHashSet class
import java.util.*; class LinkedHashSetDemo { public static void main(String args[]) { LinkedHashSet< String> hs = new LinkedHashSet< String>(); hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); } }
Output : [B, A, D, E, C, F]
TreeSet Class
- It extends AbstractSet class and implements the NavigableSet interface.
- It stores elements sorted ascending order.
- Uses a Tree structure to store elements.
- Access and retrieval times are quite fast.
- It has four Constructors.
TreeSet() TreeSet( Collection C ) TreeSet( Comparator comp ) TreeSet( SortedSet ss )
Accessing a Collection
To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection.- Using Iterator interface
- Using ListIterator interface
- Using for-each loop
Accessing elements using Iterator
Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.import java.util.*; class Test_Iterator { public static void main(String[] args) { ArrayList< String> ar = new ArrayList< String>(); ar.add("ab"); ar.add("bc"); ar.add("cd"); ar.add("de"); Iterator it = ar.iterator(); //Declaring Iterator while(it.hasNext()) { System.out.print(it.next()+" "); } } }
Output : ab bc cd de
Accessing element using ListIterator
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implement the List Interface.import java.util.*;
class Test_Iterator
{
public static void main(String[] args)
{
ArrayList< String> ar = new ArrayList< String>();
ar.add("ab");
ar.add("bc");
ar.add("cd");
ar.add("de");
ListIterator litr = ar.listIterator();
while(litr.hasNext())
//In forward direction
{
System.out.print(litr.next()+" ");
}
while(litr.hasPrevious()) //In backward direction
{
System.out.print(litr.next()+" ");
}
}
}
Output :
ab bc cd de
de cd bc ab
import java.util.*;
Using for-each loop
for-each
version of for loop can also be used for
traversing each element of a collection. But this can only be used if we
don't want to modify the contents of a collection and we don't want any
reverse access. for-each
loop can cycle through any collection of object that implements Iterable interface.import java.util.*;
class ForEachDemo
{
public static void main(String[] args)
{
LinkedList< String> ls = new LinkedList< String>();
ls.add("a");
ls.add("b");
ls.add("c");
ls.add("d");
for(String str : ls)
{
System.out.print(str+" ");
}
}
}
Output : a b c d
thank you.
ReplyDeletepython3 tutorial
Hibernate tutorial