[go: up one dir, main page]

0% found this document useful (0 votes)
75 views59 pages

Java 18-Collection Final

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 59

 Creating a collection by using generics

 Implementing an ArrayList
 Implementing a TreeSet
 Implementing a HashMap
 Implementing a Deque
 Ordering collections
Introduction
A collection is simply an object that groups multiple
elements into a single unit.

Collections are used to store, retrieve, manipulate, and


communicate aggregate data.

java.util package contains all the collection classes and


interfaces.
Collection Framework
A collections framework is a unified architecture for
representing and manipulating collections.

It is a collection of classes and interfaces.

At the top of collection framework hierarchy, there is an


interface, Collection.
Advantages of Collections
Reduces programming effort

Increases program speed and quality

Allows interoperability among unrelated APIs


Collection Interfaces
The Java Collections Framework supports two types of containers:

1.Collection: for storing a collection of elements


2.Map: for storing key/value pairs
Collection Interfaces
Sets store a group of non-duplicate elements.

Lists store an ordered collection of elements.

Queues store objects that are processed in first-in, first-out


fashion.

Maps are efficient data structures for quickly searching an


element using a key.
Collection
Interface
Methods of Collection Interface
boolean add(Object o) : Appends the specified element o to the end of
the collection.
boolean addAll(Collection c ): Appends all of the elements in the
specified collection to the end of the collection.
boolean contains(Object o) : Returns true if this list contains the
specified element.
boolean containsAll(Collection c) : Returns true if this collection
contains all the elements in c.
boolean remove(Object o) : Removes the object from this collection.
boolean removeAll(Collection c) : Removes all the elements in c from
this collection.
Methods of Collection Interface
boolean retainAll(Collection c) : Retains the elements that are both in c
and in this collection.
void clear() : Removes all of the elements from the collection.
boolean isEmpty() : Returns true if this collection contains no elements.
int size() : Returns the number of elements in the collection.
object [] toArray() : Returns an array of Object for the elements in the
collection.
int hashCode() : Returns the hash code for the collection.
Iterator iterator() : Returns the iterator object for the invoking
collection.
Iterators
Iterator
There is an Iterable interface at the top of Collection hierarchy.

The Collection interface extends the java.lang.Iterable


interface.

It defines a method which returns an Iterator object for the


elements of Collection.
Iterator iterator()

Iterator object is used to traverse the elements in a collection.


Methods of Iterator Interface
boolean hasNext() : Returns true if this iterator has more
elements to traverse.

Object next() : Returns the next element from this iterator.

void remove() : Removes the last element obtained using the


next method.
ListIterator
ListIterator
ListIterator is derived from Iterator interface and comes with
more methods than Iterator.

ListIterator can be used to traverse for List type Objects.

Allows to traverse in both the directions.


ListIterator
A ListIterator has no current element; its cursor position
always lies between the element that would be returned by a
call to previous() and the element that would be returned by a
call to next().

The remove() and set(Object) methods are not defined in terms


of the cursor position; they are defined to operate on the last
element returned by a call to next() or previous().
ListIterator Methods
public abstract boolean hasPrevious()
public abstract Object previous();

public abstract int nextIndex();


public abstract int previousIndex();

public abstract void set(Object);


public abstract void add(Object);
list Interface
List
The List interface extends the Collection interface.

It defines a collection for storing elements in a sequential


order.

It define an ordered collection with duplicates allowed.

ArrayList , Vector and LinkedList are the sub-classes of List


interface.
Methods of List Interface
• boolean add(int index, Object o )
• boolean addAll(int index, Collection c )
• Object remove(int index)
• Object get(int index)
• Object set(int index, Object o)
• int indexOf(Object o)
• int lastIndexOf(Object o)
• ListIterator listIterator()
• ListIterator listIterator(int start_index)
• List subList(int start_index, int end_index): returns a sublist from
start_index to end_index-1
Sub-classes of List

ArrayList

LinkedList

Vector

Stack
ArrayList
ArrayList
 The ArrayList class extends AbstractList and
implements the List interface.

 Defined in java.util package.

 ArrayList supports dynamic arrays that can grow as


needed.

 Array lists are created with an initial size.

 When this size is exceeded, the collection is


automatically enlarged.

 When objects are removed, the array may be


shrunk.
Fig: Hierarchy of ArrayList class
ArrayList Constructors
T he ArrayList class supports three constructors.

 ArrayList() : creates an empty array list with an initial capacity


sufficient to hold 10 elements.

 ArrayList(int capacity) : creates an array list that has the


specified initial capacity.

 ArrayList(Collection c) : creates an array list that is initialized


with the elements of the collection c.
Methods of ArrayList
boolean add(Object o) : Appends the specified element to the end of
this list.
void add(int index, Object element) : Inserts the specified element at
the specified position index in this list and throws
IndexOutOfBoundsException if the specified index is out of range.
boolean addAll(Collection c ) : Appends all of the elements in the
specified collection to the end of this list and throws
NullPointerException if the specified collection is null.
boolean addAll(int index, Collection c ) : Inserts all of the elements of
the specified collection into this list, starting at the specified position
and throws NullPointerException if the specified collection is null.
Object remove(int index) : Removes the element at the specified
position in this list.
Object remove(Object o) : Removes the element o from this list.
Methods of ArrayList cont…
Object clone() : Returns a shallow copy of this ArrayList.
int size() : Returns the number of elements in the list.
void clear() : Removes all of the elements from this list.
boolean contains(Object o) : Returns true if this list contains the
specified element.
Object get(int index) : Returns the element at the specified position in
this list.
int indexOf(Object o) : Returns the index in this list of the first
occurrence of the specified element, or -1 if the List does not contain
the element.
int lastIndexOf(Object o) : Returns the index in this list of the last
occurrence of the specified element, or -1.
Methods of ArrayList cont…
void ensureCapacity(int minCapacity) : Increases the capacity of this
ArrayList instance, if necessary, to ensure that it can hold at least the
number of elements specified by the minimum capacity argument.
Object set(int index, Object element) : Replaces the element at the
specified position in this list with the specified element and throws
IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index >= size()).
void trimToSize() : Trims the capacity of this ArrayList instance to be the
list’s current size.
Implementing an ArrayList
import java.util.*;
class TestArrayList{
public static void main(String [] args){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Set Interface
Set Interface
 A set is an efficient data structure for storing and processing
non-duplicate elements.

Set does not introduce new methods or constants.

The sub-classes of Set (HashSet, TreeSet & LinkedHashSet)


ensure that no duplicate elements can be added to the set.
Set Interface
The AbstractSet class provides implementations for the
equals() method and the hashCode().

The hash code of a set is the sum of the hash codes of all the
elements in the set.

The size() and iterator() are not implemented in the


AbstractSet class.
TREESet
TreeSet
TreeSet implements the NavigableSet
interface.

We can add objects into a tree set as long as


they can be compared with each other.

Access and retrieval times are quite fast.

Fig: Hierarchy of TreeSet class


TreeSet Constructor
TreeSet Methods
Implementing TreeSet
import java.util.*;
public class TestTreeSet{
public static void main(String args[]){
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
MAP Interface
MAP Interface
A map is a container object that stores a collection of key/value
pairs.

Keys are like indexes in List but in Map, the keys can be any
objects.

A map cannot contain duplicate keys.

Each key maps to one value.

A key and its corresponding value form an entry stored in a map.


MAP
MAP Methods
HashMap
The HashMap class is efficient for locating a value, inserting an
entry, and deleting an entry.
The entries in a HashMap are not ordered.

Fig: Hierarchy of HashMap class


HashMap Constructors
HashMap()
Constructs an empty HashMap with the default initial capacity (16) and
the default load factor (0.75).
HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the
default load factor (0.75).
HashMap(int initialCapacity, float loadFactor)
Constructs an empty HashMap with the specified initial capacity and
load factor.
HashMap(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.
HashMap Methods
Implementing a HashMap
import java.util.*;
public class HashMapExample {
public static void main(String []args) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(101, "Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
DEQue
Deque Interface
Deque supports element insertion and removal at both ends.

The name deque is short for “double-ended queue” and is usually


pronounced “deck.”

The Deque interface extends Queue with additional methods for


inserting and removing elements from both ends of the queue.
Deque Methods
Insert Methods
The addfirst and offerFirst methods insert elements at the
beginning of the Deque instance.

The methods addLast and offerLast insert elements at the


end of the Deque instance.

When the capacity of the Deque instance is restricted, the


preferred methods are offerFirst and offerLast because
addFirst might fail to throw an exception if it is full.
Remove Methods
removeFirst and pollFirst methods remove elements from
the beginning of the Deque.

The removeLast and pollLast methods remove elements


from the end.

The methods pollFirst and pollLast return null if the


Deque is empty whereas the methods removeFirst and
removeLast throw an exception if the Deque instance is
empty.
Retrieve Methods
getFirst and peekFirst retrieve the first element but don’t
remove the value from the Deque.

Similarly, getLast and peekLast retrieve the last element.

The methods getFirst and getLast throw an exception if


the deque instance is empty whereas the methods
peekFirst and peekLast return NULL.
Deque Implementation
Predefined classes like ArrayDeque and LinkedList implement
the Deque interface.
The ArrayDeque class is the resizable array, whereas the
LinkedList class is the list implementation.
The LinkedList is more flexible than the ArrayDeque as null
elements are allowed in the LinkedList implementation but not in
ArrayDeque.
ArrayDeque is more efficient than the LinkedList for add and
remove operation at both ends.
The best operation in a LinkedList implementation is removing the
current element during the iteration.
ArrayDeque Constructors
ArrayDeque() : Constructs an empty array deque with
an initial capacity sufficient to hold 16 elements.

ArrayDeque(Collection<? extends E> c) :


Constructs a deque containing the elements of the
specified collection, in the order they are returned by
the collection's iterator.

ArrayDeque(int numElements) : Constructs an
empty array deque with an initial capacity sufficient to
hold the specified number of elements.

Fig: ArrayDeque Hierarchy


LinkedList Constructors
LinkedList() : Constructs an empty LinkedList.

LinkedList(Collection<? extends E> c) :


Constructs a list containing the elements of the
specified collection, in the order they are
returned by the collection's iterator.

Fig: Hierarchy of LinkedList class


Implementing a
Deque(ArrayDeque)
import java.util.*;
public class DequeExample {
public static void main(String[] args) {
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Implementing a Deque(LinkedList)
import java.util.*;
public class TestLinkedList{
public static void main(String []args){
Deque<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ordering collections
Comparator Interface
 Java Comparator interface is used to order the objects of
user-defined class.
java.util.Comparator interface provides two abstract
methods:
public interface Comparator<T>{
public abstract int compare(T ob1, T ob2);
public abstract boolean equals(java.lang.Object);

}
It provides multiple sorting sequence i.e. we can sort the
elements on the basis of any data member, for example
rollno, name, age or anything else.
Example:
class RectangleComparator implements Comparator<Rectangle>{
public int compare(Rectangle x, Rectangle y){
int perimeter1=x.perimeter();
int perimeter2=y.perimeter();
if(perimeter1<perimeter2)
return +1;
else{
if(perimeter1>perimeter2)
return -1;
else
return 0;
}
}
}
Program link: TestTreeSetWithComparator.java
Thank You

You might also like