I faced lot of problems while creating my first application using Collections . So i decided to write a blog detailing how developers can create their application using collection by avoiding the problems that i faced while developing my application.
Introduction to the Collections Framework:
The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection.Collections are used to store, retrieve, manipulate, and communicate aggregate data. The framework provides a convenient API to many of the abstract data types familiar from computer science data structure curriculum: maps, sets, lists, trees, arrays, hashtables and other collections.
skipping definitions.........
What Is a Collections Framework?:
The Collections Framework is made up of a set of interfaces for working with groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. The following diagrams shows the framework interface hierarchy.
- Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages, interfaces generally form a hierarchy.
- Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.
- Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality.
The following diagrams shows the framework interface hierarchy.
ListInterface:
The
Listinterface extends theCollectioninterface to define an ordered collection, permitting duplicates.The interface adds position-oriented operations, as well as the ability to work with just a part of the list.
The position-oriented operations include the ability to insert an element or
Collection, get an element, as well as remove or change an element.Searching for an element in a
Listcan be started from the beginning or end and will report the position of the element, if found.
Allocating an ArrayList:
By default, ArrayList objects are allocated to be large enough to hold only a few objects. When the limit is reached, a new ArrayList is allocated larger than the previous one and the old ArrayList is copied to the new ArrayList.
Example On ArrayList
package com.example.collections;import java.util.ArrayList;
import java.util.LinkedList;
/**
* @author DilipLogictree
*
*/
public class ListExample {
// Statics
public static void main(String args[])
{
//Create a collection
ArrayList<String> list=new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("b");
list.add("c");
System.out.println("List Created");
//add using indexes
list.add(3, "d");
System.out.println("adding new element to index 3: element added is= "+list.get(3));
//Removing
list.remove(4);
System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
// Sizing
System.out.println("Elements In List Are:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}
}
With the ArrayList class the default initial capacity is 10 and the formula to increase the capacity of the ArrayList each time it reaches its limit is (oldCapacity * 3)/2 + 1.
OutPut:
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d
package com.example.collections;
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d
what is the difference between linkedlist and arraylist?
The difference is in the performance characteristics. Because of the way ArrayList and LinkedList work internally, some operations are more efficient on ArrayList, and some operations are more efficient on LinkedList.
For example, inserting an element in the middle of the list is relatively slow on ArrayList, but fast on LinkedList. And looking up a random element in the list is fast on ArrayList, but slow on LinkedList .
package com.example.collections;
while(itr.hasNext())
OutPut
The
package com.example.collections;
Values in hashset :[50, 20, 40, 10, 30, 60]
package com.example.collections;
package com.example.collections;
The HashMap is a class which is used to perform some basic operations such as inserting, deleting, and locating elements in a
package com.example.collections;
The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to a HashMap , then convert the map to a TreeMap for traversing the sorted keys.
LinkedHashMap
A LinkedHashMap is implemented using both Hash table and linked list implementation of the Map interface. This implementation differs from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).
OutPut:
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d
Allocating an LinkedList:
The implementation of a LinkedList is a doubly-linked list. That is, when the list needs to expand, it allocates a new block and adds a link from the end of the original block to the new block and from the new block to the original block. In this way the list can be traversed in either direction. The LinkedList is very efficient at insertions into and deletions from the list. It also performs very well when iterating through the list.
package com.example.collections;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* @author DilipLogictree
*
*/
public class ListExample {
// Statics
public static void main(String args[])
{
//Create a collection
LinkedList<String> list=new LinkedList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("b");
list.add("c");
System.out.println("List Created");
//add using indexes
list.add(3, "d");
System.out.println("adding new element to index 3: element added is= "+list.get(3));
//Removing
list.remove(4);
System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
// Sizing
System.out.println("Elements In List Are:");
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}
}
OutPut:
List Createdadding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are:
a
b
c
d
what is the difference between linkedlist and arraylist?
The difference is in the performance characteristics. Because of the way ArrayList and LinkedList work internally, some operations are more efficient on ArrayList, and some operations are more efficient on LinkedList.
For example, inserting an element in the middle of the list is relatively slow on ArrayList, but fast on LinkedList. And looking up a random element in the list is fast on ArrayList, but slow on LinkedList .
Listlterator interface
The Listlterator is a child of the Iterator interface and adds additional functionality that the Iterator interface does not provide. The additional methods allow for reverse traversing of the collection and for inserting or replacing elements from the collection. The Listlterator includes all the methods of the Iterator interface and adds these methods.
Example On ListIterator
package com.example.collections;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* @author DilipLogictree
*
*/
public class ListExample {
// Statics
public static void main(String args[])
{
//Create a collection
LinkedList<String> list=new LinkedList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("b");
list.add("c");
System.out.println("List Created");
//add using indexes
list.add(3, "d");
System.out.println("adding new element to index 3: element added is= "+list.get(3));
//Removing
list.remove(4);
System.out.println("Removing element fom index 4: element rempved is= "+list.remove(4));
// Sizing
System.out.println("Elements In List Are:");
ListIterator<String> itr=list.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
OutPut
List Created
adding new element to index 3: element added is= d
Removing element fom index 4: element rempved is= c
Elements In List Are: Using ListIterator
a
b
c
d
SetInterface
The Set interface extends the Collection interface. It neither contains duplicate elements nor maps a key value to an object. It permits a single element to be null.
The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
HashSet
This is a class which stores its elements in a hash table and doesn't allow to store duplicate collections. This class permits the null element and is used to perform the basic operations such as add, remove, contains and size.
Example
package com.example.collections;
import java.util.HashSet;
/**
* @author DilipLogictree
*
*/
public class SetExample {
//Statics
public static void main(String args[])
{
int count[]={50,60,20,10,40,30,30};
//Create Collection
HashSet hash=new HashSet();
//add values
for(int i=0;i<=6;i++)
{
hash.add(count[i]);
}
//print values
System.out.println("Values in hashset :"+hash);
}
}
OutPut
Values in hashset :[50, 20, 40, 10, 30, 60]
TreeSet
The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. The elements added to a TreeSet are sortable in an order. It is generally faster to add elements to a HashSet, then converting the collection to a TreeSet for sorted traversal.
Example
package com.example.collections;
import java.util.HashSet;
import java.util.TreeSet;
/**
* @author DilipLogictree
*
*/
public class SetExample {
//Statics
public static void main(String args[])
{
int count[]={50,60,20,10,40,30,30};
//Create Collection
TreeSet tree=new TreeSet();
//add values
for(int i=0;i<=6;i++)
{
tree.add(count[i]);
}
//print values
System.out.println("Values in treeset :"+tree);
}
}
OutPut
Values in treeset :[10, 20, 30, 40, 50, 60]
LinkedHashSet
It is a class which is implements both the Hash table and linked list implementation of the Set interface. This implementation differs from HashSet that it maintains a doubly-linked list. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).
Example
package com.example.collections;
import java.util.LinkedHashSet;
/**
* @author DilipLogictree
*
*/
public class SetExample {
//Statics
public static void main(String args[])
{
int count[]={20,10,40,30,60,50,70};
//Create Collection
LinkedHashSet<Integer> linkedset=new LinkedHashSet<Integer>();
//add values
for(int i=0;i<=6;i++)
{
linkedset.add(count[i]);
}
//print values
System.out.println("Values in LinkedHashSet :"+linkedset);
}
}
OutPut
Values in LinkedHashSet :[20, 10, 40, 30, 60, 50, 70]
Map Interface
A Map is an object that maps keys to values. It is not an extension of the collection interface rather it has Own interface hierarchy. Map provides a more general way for storing elements without containing duplicate keys. It allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Thus the keys in a map must be unique.
HashMap
The HashMap is a class which is used to perform some basic operations such as inserting, deleting, and locating elements in a Map . The java.util.HashMap class is implemented with and roughly equivalent to a Hashtable except that it is unsynchronized and permits null. It works with the Iterators requires a well-defined implementation of the method hashCode( ).
Example
package com.example.collections;
import java.util.HashMap;
public class MapExample {
public static void main(String args[]){
HashMap<Integer, String> map=new HashMap<Integer, String>();
String name[]={"a,b,c,d,f,g,s,s,s,a,z,q,p"};
for(int i=0;i<name.length;i++)
{
map.put(i, name[i]);
}
System.out.println(map);
}
}
OutPut
values in map{0=a,b,c,d,f,g,s,s,s,a,z,q,p}
TreeMap
The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to a HashMap , then convert the map to a TreeMap for traversing the sorted keys.
LinkedHashMap
A LinkedHashMap is implemented using both Hash table and linked list implementation of the Map interface. This implementation differs from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).
