Chapter 1 - Collections and Generics
Chapter 1 - Collections and Generics
Chapter 1 - Collections and Generics
each key can map to at most one value. Although, it does not
ensure element ordering, some implementations guarantee it. To
interoperate with other collection classes/interfaces, it provides
three collection views, which allow a map's contents to be
viewed as a set of keys, collection of values, or set of key-value
mappings.
Collection
A collection is a container that encapsulates
multiple objects into a single unit, such as a
list of employees, a set of numbers, a set of,
processes, a queue of requests etc..
All the collection classes are available in
the package called 'java.util’
Group of collection classes is called a
Collection Framework.
Some examples of collections are
the cards you hold in a card game,
your favorite songs stored in your
computer,
the members of a sports team and
Collection Interface
Defines fundamental methods
int size();
boolean isEmpty();
Iterator iterator();
System.out.println(c.getClass().getName());
Output:
for (int i=1; i <= 10; i++) { java.util.ArrayList
c.add(i + " * " + i + " = "+i*i);
1*1=1
} 2*2=4
3*3=9
Iterator iter = c.iterator(); 4 * 4 = 16
while (iter.hasNext()) 5 * 5 = 25
6 * 6 = 36
System.out.println(iter.next());
7 * 7 = 49
} 8 * 8 = 64
} 9 * 9 = 81
10 * 10 = 100
List Interface
List
void add(Object o)
boolean hasPrevious()
Object previous()
The indexed get and set methods of the List interface are
treeMap]
null insertion are possible
Example: ArrayList
import java.util.*;
class ArrayListDemo
{ public static void main(String args[])
{ ArrayList <String> al = new ArrayList<String>();
al.add (“Sheger"); al.add (“Adama");
al.add (“Hawassa"); al.add (“BahirDar");
al.add (“Mekele");
al.add (1,“DireDawa");
al.add (2,“Asosa");
System.out.print("Size of the Array List is: " + al.size ());
System.out.print("\nRetrieving elements in ArrayList using Itera
Iterator it = al.iterator ();
while (it.hasNext () )
System.out.print (it.next () + "\t");
}}
LinkedList
This class implements two collection interfaces, List
and Deque and provides all operations of these two
interfaces. It inherits the AbstractList class and
implements List and Deque interfaces.
It uses a doubly linked list internally to store the
elements.
It provides a linked-list data structure.
Important points:
o LinkedList class can contain duplicate
elements.
o LinkedList class maintains insertion
order.
o It is non synchronized.
o Its manipulation is fast because no
LinkedList Methods
Example: LinkedList
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> pl=new LinkedList<String>();
pl.add(“Java");
pl.add(“Python");
pl.add(“C++");
pl.add(“C#");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Vector
• Vectors are similar to arrays, where the elements of
the vector object can be accessed via an index into
the vector. Vector implements a dynamic array. Also,
the vector is not limited to a specific size, it can shrink
or grow automatically whenever required. It is similar
to ArrayList, but with two differences :
Vector is synchronized.
Vector contains many legacy methods that are not part of the
collections framework.
Some legacy methods in vector class
import java.util.*;
public class Vector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>()
;
v.add(“SoEEC"); import java.util.*;
v.add(“SoMMCE"); public class LegVector1 { public static
void main(String ar[])
v.add(“SoCEA");
{ Vector<String> vec= new
v.add(“SoANC"); Vector<String>(); vec.addElement("B");
Iterator<String> itr=v.iterator();
vec.addElement("A"); vec.addElement("T");
while(itr.hasNext()){ vec.addElement("M"); vec.addElement("A");
System.out.println(itr.next()); }}}
vec.addElement("N");
System.out.println("Vector = "+vec);
System.out.println("Size of Vector = "+
vec.size()); System.out.println("First element
in Vector = "+vec.firstElement());
System.out.println("Last element in Vector =
"+vec.lastElement());
System.out.println("Element at 2nd index =
"+ vec.elementAt(2));
vec.removeElementAt(2);
System.out.println("After removing element
Stack
• The stack is the subclass of Vector. It implements the
last-in-first-out data structure, i.e., Stack. The stack
contains all of the methods of Vector class and also
provides its methods like boolean push(), boolean
import
pop(), java.util.*;
boolean peek() which defines its properties.
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push(“SoEEC");
stack.push(“SoMMCE");
stack.push(“SoCEA");
stack.push(“SoANC");
stack.push(“SoHSS");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}}}
Set Interface
Same methods as Collection
TreeSet.
Set
called hashing.
contains unique elements only.
non synchronized.
keys.
A Map is useful if you have to search, update or delete elemen
basis of a key.
You can create a map using one of its three concrete classes:
HashMap,
LinkedHashMap, or TreeMap.
Map Methods
Map.Entry interface
Entry is the subinterface of Map. So,will be accessed it by Map.Entry
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Generic Class and Methods
Generic Class: A class that can refer to any type
is known as generic class. Here, we are
using T type parameter to create the generic class
of specific type.
Type Parameters: the commonly type
parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value
Creating Generic Class
class MyGen<T>{
T obj;
void add(T obj)
{
this.obj=obj;
}
T get()
{
return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, Employee etc.).
The type you specify for the class, will be used to store and retrieve the data.
Using Generic Class