Sunteți pe pagina 1din 29

1

Java Collection API


2
Overview of Collection
A collection is a group of data manipulate as a single
object.Corresponds to a bag.
Insulate client programs from the implementation. array, linked
list, hash table, balanced binary tree.
Like C++'s Standard Template Library (STL)
Can grow as necessary.
Contain only Objects (reference types).
Heterogeneous.
Can be made thread safe (concurrent access).
Can be made not-modifiable
2
Collection Interfaces

5
/
2
9
/
2
0
1
4

2
The Collection Interface
/ / For Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element);
boolean remove(Object element); //
Iterator iterator();
2
The Collection Interface
//for Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c);
boolean removeAll(Collection c);
boolean retainAll(Collection c);
void clear();
2
The List Interface
The List interface corresponds to an order group of elements.
Duplicates are allowed.
Extensions compared to the Collection interface
Access to elements via indexes, like arrays
add (int, Object), get(int), remove(int),
set(int, Object) (note set = replace bad name for the method)
Search for elements
indexOf(Object), lastIndexOf(Object)
Specialized Iterator, call ListIterator
Extraction of sublist
subList(int fromIndex, int toIndex)
2
The List Interface, cont.
Further requirements compared to the Collection
Interface
add(Object)adds at the end of the list.
remove(Object)removes at the start of the list.

list1.equals(list2) the ordering of the elements is taken
into consideration.
list1.equals(list2) implies that
list1.hashCode()==list2.hashCode()
2
The List Interface, cont.
public interface List extends Collection {
// Positional Access
Object get(int index);
Object set(int index, Object element); // Optional
void add(int index, Object element); // Optional
Object remove(int index); // Optional
abstract boolean addAll(int index, Collection c);
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator();
ListIterator listIterator(int index);
}
2
ArrayList Class
The classes ArrayList and LinkedList implement the List
interface.
ArrayList is an array based implementation where elements can be
accessed directly via the get and set methods.
Default choice for simple sequence.
It uses a dynamic array for storing the elements.
It can contain duplicate elements.
It maintains insertion order.
It is not synchronized.
It allows random access because array works at the index basis.
Its manipulation is slower because a lot of shifting needs to be
occurred.

Example: arraylist
import java.util.*;
class Simple{
public static void main(String args[]){

ArrayList al=new ArrayList();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

5
/
2
9
/
2
0
1
4

for(Object obj:al)
System.out.println(obj);
Example: ArrayList storing user defined objects
import java.util.*;
class Simple{
public static void main(String args[]){

Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);

ArrayList al=new ArrayList();
al.add(s1);
al.add(s2);
al.add(s3);

Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}

5
/
2
9
/
2
0
1
4

2
LinkedList Classes
LinkedList is based on a double linked list
Gives better performance on add and remove compared to
ArrayList.
Gives poorer performance on get and set methods compared
toArrayList.
It can contain duplicate elements.
It maintains insertion order.
It is not synchronized.
No random access.
It can be manipulated faster because no shifting needs to be
occurred.
It can be used as list, stack or queue.

2
LinkedList Example
import java.util.*;
class Simple{
public static void main(String args[]){

LinkedList al=new LinkedList();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
}
2
The Set Interface
Corresponds to the mathematical definition of a set (no
duplicates are allowed).
Compared to the Collection interface
Interface is identical.
Every constructor must create a collection without
duplicates.
The operation add cannot add an element already in
the set.
The method call set1.equals(set2) works at follows
set1 union set2, and set2 union set1.
2
HashSet and TreeSet Classes
HashSet and TreeSet implement the interface
Set.
HashSet
Implemented using a hash table.
No ordering of elements.
add, remove, and contains methods constant
time complexityO(c).

Ex: HashSet
import java.util.*;
class Simple{
public static void main(String args[]){
HashSet al=new HashSet();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

5
/
2
9
/
2
0
1
4

LinkedHashSet
It contains unique
elements only like
HashSet. It extends
HashSet class and
implements Set
interface.
It maintains insertion
order.

5
/
2
9
/
2
0
1
4

import java.util.*;
class Simple{
public static void main(String args[]){

LinkedHashSet al=new LinkedHashSet();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
2
TreeSet
Implemented using a tree structure.
Guarantees ordering of elements.(maintains
ascending order)
add, remove, and contains methods
logarithmic time complexityO(log (n)), where
n is the number of elements in the set.
Ex: TreeSet
import java.util.*;
class Simple{
public static void main(String args[]){

TreeSet al=new TreeSet();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

5
/
2
9
/
2
0
1
4

2
Map Interface
A Map is an object that maps keys to values. Also called an
associative array or a dictionary.
Methods for adding and deleting
put(Object key, Object value)
remove (Object key)
Methods for extraction objects
get (Object key)
Methods to retrieve the keys, the values, and (key, value) pairs
keySet() // returns a Set
values() // returns a Collection,
entrySet() // returns a set
2
MAP Interface methods
public interface Map {
// Basic Operations
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk Operations
void putAll(Map t);
void clear();
// Collection Views
public Set keySet();
public Collection values();
public Set entrySet();

2
HashMap and TreeMap Classes
The HashMap and TreeMap classes implement the Map
interface.
HashMap
The implementation is based on a hash table.
No ordering on (key, value) pairs.
A HashMap contains values based on the key.
It contains only unique elements.
It may have one null key and multiple null values.

EX: HashMap
import java.util.*;
class Simple{
public static void main(String args[]){

HashMap hm=new HashMap();

hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

Set set=hm.entrySet();
Iterator itr=set.iterator();

while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

5
/
2
9
/
2
0
1
4

2
TreeMap
The implementation is based on tree structure.
(key, value) pairs are ordered on the key.(ascending)
A TreeMap contains values based on the key.
It contains only unique elements.
It cannot have null key but can have multiple null values.
It is same as HashMap instead maintains ascending order.

Ex: TreeMap
import java.util.*;
class Simple{
public static void main(String args[]){

TreeMap hm=new TreeMap();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");

Set set=hm.entrySet();
Iterator itr=set.iterator();

while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

5
/
2
9
/
2
0
1
4

2
Utility methods of Collections
All the methods of class Collections are static.
Search and sort: binarySearch(), sort()
Reorganization: reverse(), shuffle()
Wrappings: unModifiableCollection,
synchonizedCollection
2
Collection Advantages & disadvantages
Advantages:
Can hold different types of objects.
Resizable

Disadvantages
Must cast to correct type
Cannot do compile-time type checking.
Thank You

S-ar putea să vă placă și