Professional Documents
Culture Documents
Limitations of Object Arrays: Collection Framework in Java
Limitations of Object Arrays: Collection Framework in Java
collections shows
worst performance.
4) Collections can hold
heterogeneous data
elements.
5) Every Collection class has built
by using some
Data structure.
Constructors:
1. LinkedList l = new LinkedList()
2. LinkedList l = new LinkedList(Collection c)
For inter conversion between collection objects
Ex:
import java.util.*;
class LinkedListDemo{
public static void main(String arg[]){
LinkedList l = new LinkedList();
l.add("raju");
l.add(new Integer(10));
l.add(null);
l.add("raju");
l.set(0, "chinna");
l.add(0, "Kiran");
l.addFirst("AAAA");
l.addLast("ZZZZ");
System.out.println(l);
}}
Inter conversion between collection objects.
ArrayList al = new ArrayList();
l1.add(10);
l1.add(20);
l1.add(30);
System.out.println("l1--->"+l1);
LinkedList l2 = new LinkedList(l1);
l2.add(1,5);
l2.add(3,5);
l2.add(5,15);
System.out.println("l2--->"+l2);
ArrayList l3 = new ArrayList(l2)
System.out.println("l3--->"+l3);
VectorClass:The underlying Data structure for the vector is resizable array
or growable array.
Insertion order is preserved.
Duplicate objects are allowed.
null insertion is possible.
Heterogeneous objects are allowed.
Vector methods:
add(Object obj)
add(int index, Object obj)
addElement(Object obj)
remove(Object obj)
removeElement(Object obj)
remove(int index)
removeElementAt(int index)
clear()
removeAllElements()
Object get(int index)
Object elementAt(int index)
Object firstElement();
Object lastElement();
int size();
int capacity();
Enumaration elements();
Constructors in Vector:
Vector v = new Vector();
Creates an empty vector object with default initial capacity 10, when ever
vector reaches its max capacity a new vector object will be created with.
new capacity = 2 * current capacity
Vector v = new Vector(int initialCapacity)
Vector v = new Vector(int initialCapacity, int incrementalCapacity)
Vector v = new Vector(Collection c)
Ex:
import java.util.*;
class VectorDemo{
public static void main(String arg[]){
Vector v = new Vector();
System.out.println(v.capacity());
for (int i = 0;i<10 ;i++ ){
v.addElement(i);
}
System.out.println(v.capacity());
System.out.println(v);
}}
Cursors Available in collection frame work
From the collection object to retrieve object we can use the following 3
cursors.
1. Enumeration
2. Iterator
3. ListIterator
Enumeration:This interface has introduced in 1.0 version it contains the
following 2 methods.
boolean hasMoreElements();
Object nextElement();
Ex:
import java.util.*;
class EnumaretionDemo{
public static void main(String arg[]){
Vector v = new Vector();
for (int i =0;i<=10 ;i++ ){
v.addElement(i);
}
System.out.println(v);
Enumeration e = v.elements();
while (e.hasMoreElements()){
Integer i = (Integer)e.nextElement();
if((i%2) == 0)
System.out.println(i);
}
System.out.println(v);
}}
Limitations of Enumeration
1. It is applicable only for legacy classes and it is not a universal cursor.
2. While iterating the elements by using enumeration we can perform only
read operation and we cant perform any modify/removal operations.
To overcome these problems we should go for Iterator interface.
Iterator :Introduced in 1.2 version.
We can get Iterator Object for any collection incremented class i.e it is
universal cursor.
By iterating the elements we can perform remove operation also in addition
to read operation.
This interface contains the following 3 methods.
boolean hasNext();
Object next();
void remove();
Ex:
import java.util.*;
class IteratorDemo{
public static void main(String arg[]){
ArrayList al = new ArrayList();
for (int i =0;i<=10 ;i++ ){
al.add(i);
}
System.out.println(al);
Iterator itr = al.iterator();
while (itr.hasNext()){
Integer i = (Integer)itr.next();
if((i%2) == 0){
System.out.println(i);
}
else{
itr.remove();
}}
System.out.println(al);
}}
Note:1. Enumeration and Iterator are single directional cursors. They can always
move to words forward direction only.
SortedSet:
This can be used for representing a group of individual objects where
duplicate objects are not allowed.
Insertion order is not preserved but all the elements are inserted according
to some sorting order of elements. The sorting order may be default natural
sorting order or customized sorting order.
TreeSet
The underlying Data structure for the TreeSet is Balanced tree.
Duplicate objects are not allowed. If we are trying to insert duplicate object
we wont get any compile time error or Run time error, add method simply
returns false.
Insertion order is not preserved but all the elements are inserted according
to some sorting order.
Heterogeneous objects are not allowed, violation leads to Run time error
saying class cast Exception
Constructors:
1. TreeSet t = new TreeSet();
Creates an empty TreeSet Object where the sorting order is default natural
sorting order.
2. TreeSet t= new TreeSet(Comparator c)
Creates an empty TreeSet Object where the Sorting order is specified by
comparator object.
3. TreeSet t= new TreeSet(Collection c)
4. TreeSet t= new TreeSet(SortedSet s)
import java.util.*;
class TreeSetDemo {
public static void main(String arg[]){
TreeSet t = new TreeSet();
t.add("A");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10)); - ClassCastException.
//t.add(null); - NullPointerException.
t.add("A"); - false.
System.out.println(t);
}}
null Acceptance:
For the empty TreeSet as the first element null insertion is possible. But
after inserting null if we are trying to insert any other element we will get
NullPointerException.
If the TreeSet already contains some elements if we are trying to insert null
we will get NullPointerException.
Ex:
import java.util.*;
class TreeSetDemo{
public static void main(String arg[]){
TreeSet t = new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("B"));
t.add(new StringBuffer("T"));
t.add(new StringBuffer("Z"));
System.out.println(t);
}}
O/P:- R.E: ClassCastException.
If we are depending on natural sorting order compulsory the objects should
be homogeneous and comparable other wise we will get class cast
Exception.
An object is said to be comparable(if and only if) the corresponding class has
to implement comparable interface.
Comparable Interface:
It is available in java.lang package. This interface contains only one method
compareTo()
public int compareTo(Object obj)
obj1.compareTo(obj2)
return ve if obj1 has to come before obj2.
+ ve if obj1 has to come after obj2.
0 if obj1 and obj2 are equal(Duplicate Objects).
Ex:
System.out.println("A".compareTo("Z")); - -ve
System.out.println("K".compareTo("A")); - _ve
System.out.println("K".compareTo("K")); - 0
System.out.println("a".compareTo("A")); - +ve
return 0;}}
Map Interface:
The Map interface is not an extension of Collection interface. Instead the
interface starts of its own interface hierarchy, for maintaining key-value
associations. The interface describes a mapping from keys to values, without
duplicate keys, by defination.
1)Map implemented by HashMap and TreeMap
2)SortedMap implemented by TreeMap.
Key-Value pairs:
Key-value pairs are stored in maps.
Map interfaces:
1. Map implemented by HashMap and TreeMap
2. SortedMap implemented by TreeMap.
3.Map.Entry which describes access methods to the key-value pairs.
Implementing classes:
A number of classes implement the Map interface, including HashMap,
TreeMap, LinkedHashMap,WeakHashMap, ConcurrentHashMap, and
Properties. The most generally useful class is HashMap.
1. java.util.HashMap is implemented with a hash table.
2. java.util.LinkedHashMap is implemented with a hash table.
3. java.util.TreeMap is implemented as a balanced binary tree.
Map Interface Methods:
1.void clear( )
Removes all key/value pairs from the invoking map.
2.boolean containsKey(Object k)
Returns true if the invoking map contains k as a key. Otherwise, returns
false.
3.boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise, returns false.
4.Set entrySet( )
Returns a Set that contains the entries in the map. The set contains objects
of type Map.Entry. This method provides a set-view of the invoking map.
1.Object getKey( )
Returns the key for this map entry.
2.Object getValue( )
Returns the value for this map entry.
3.Object setValue(Object v)
Sets the value for this map entry to v.
A ClassCastException is thrown if v is not the correct type for the map. A
NullPointerException is thrown if v is null and the map does not permit null
keys. An UnsupportedOperationException is thrown if the map cannot be
changed.
HashMap
HashMap is not sorted or ordered. If you just need a Map, and you dont
care about the order of the elements while iterating through it, you can use
a HashMap. That keeps it simple. The values can be null. But the key should
ne unique, so you can have one null value for key. (Allows only one null
key).
HashMap class constructors:
HashMap h = new HashMap();
HashMap h = new HashMap(initial Capacity);
HashMap h = new HashMap(int initial Capacity,float fillRatio);
HashMap h = new HashMap(Map m);
TreeMap
TreeMap is a sorted Map and will be sorted by the natural order of the
elements. If you want, you can define a custom sort order by means of a
Comparator passed to the constructor. So, when you need a custom sort
order, it is clear which class you should be using!
TreeMap class constructors
1. TreeMap t = new TreeMap();
Creates an empty TreeMap Object where the sorting order is default natural
sorting order.
2. TreeMap t= new TreeMap(Comparator c)
Creates an empty TreeMap Object where the Sorting order is specified by
comparator object.
3. TreeMap t= new TreeMap(Collection c)
4. TreeMap t= new TreeMap(SortedMap s)