Collections & ArrayList - 1
Collections & ArrayList - 1
2
COLLECTION HIERARCHY
3
TCS CONFIDENTIAL
Collection : Root interface with basic methods like add(), remove(),
contains(), isEmpty(), addAll(), ... etc.
4
5
6
7
General-purpose Implementations
Interfaces Implementations
Hash table Resizable array Tree Linked list Hash table + Linked list
(sorted)
TreeSet
Set HashSet (sorted) LinkedHashSet
LinkedList
List ArrayList
Queue
TreeMap
Map HashMap (sorted) LinkedHashMap
LinkedList also implements queue and there is a PriorityQueue implementation (implemented with heap)
8
The Collection interface – basic operations
• Basic operations in collection interface:
–int size(): returns the number of elements in the collection
–boolean isEmpty(): checks if a collection is empty
–boolean contains(Object element): checks whether a given
object is present in the collection
–boolean add(Object element): adds given element to the
collection.
–boolean remove(Object element): removes an element from the
collection
–Iterator<E> iterator: provides an iterator over the collection
9
The Collection interface – bulk operations
• containsAll — returns true if the target Collection contains all of
the elements in the specified Collection.
• addAll — adds all of the elements in the specified Collection to the
target Collection.
• removeAll — removes from the target Collection all of its elements
that are also contained in the specified Collection.
• retainAll — removes from the target Collection all its elements that
are not also contained in the specified Collection. That is, it retains
only those elements in the target Collection that are also
contained in the specified Collection.
• clear — removes all elements from the Collection.
10
The Collection interface – traversing collections
•for-each Construct
Allows to traverse through a collection.
for(Object o: collection)
{
//code
}
•Iterators
An iterator is an object that enables t traverse through a collection
and to remove elements from the collection selectively, if required.
– Iterator interface has following methods
• boolean hasNext(): returns true if the iteration has more
elements
• Object next(): returns the next element in the iteration
• void remove(): removes the last element that was returned by
call of next() on the collection. The remove method can be
called only once per call to next(). 11
LIST
12
TCS CONFIDENTIAL
public interface List<E>
extends Collection<E>
13
public interface List<E>
extends Collection<E>
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view
List<E> subList(int from, int to);
}
14
ARRAYLIST
15
TCS CONFIDENTIAL
METHODS OF ARRAYLIST
import java.util.ArrayList;
public class MyBasicArrayList {
public static void main(String[] a){
ArrayList<String> al = new ArrayList<String>();
//add elements to the ArrayList
al.add("JAVA");
al.add("C++");
al.add("PERL");
al.add("PHP");
System.out.println(al);
//get elements by index
System.out.println("Element at index 1: "+al.get(1));
System.out.println("Does list contains JAVA?
"+al.contains("JAVA"));
16
TCS CONFIDENTIAL
METHODS OF ARRAYLIST
//add elements at a specific index
al.add(2,"PLAY");
System.out.println(al);
System.out.println("Is arraylist empty? "+al.isEmpty());
System.out.println("Index of PERL is "+al.indexOf("PERL"));
System.out.println("Size of the arraylist is: "+al.size());
}}
OUTPUT:
[JAVA, C++, PERL, PHP]
Element at index 1: C++
Does list contains JAVA? true
[JAVA, C++, PLAY, PERL, PHP]
Is arraylist empty? false
Index of PERL is 3
Size of the arraylist is: 5
17
TCS CONFIDENTIAL
A sample code using ArrayList
import java.util.*;
class Company
{
ArrayList<Employee> employeeRegister = new ArrayList<Employee>();
class Employee
{ Company techSmart = new Company()
private String empNo; Employee emp1 = new Employee("121","Bob")
private String name;
Employee emp2 = new Employee("232","Linda")
Employee(String empNo, String name)
techSmart.addEmployee(emp1)
{ techSmart.addEmployee(emp2)
this.name = name; techSmart.modifyEmployeeName("121","Bob Jr.")
this.empNo = empNo; emp1.name
} "Bob Jr."
public String getEmpNo()
{return empNo;}
19
Link list
20
LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It provides a
linked-list data structure. It inherits the AbstractList class and implements List and
Deque interfaces.
21
public interface Set<E>
extends Collection<E>
22
public interface Set<E>
extends Collection<E>
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
24
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
25
LinkedHashSet
26
TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet
class are stored in ascending order.
27
public interface Map<K,V>
28
public interface Map<K,V>
public interface Map<K,V> {
// Basic operations
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk operations
void putAll(Map<? extends K, ? extends V> m);
void clear();
// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();
Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.
⚫ A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
⚫ contains unique elements.
⚫ doesn't allow null key or value.
⚫ is synchronized and is legacy
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} 30
}
Java HashMap class
Java HashMap class implements the map interface by using a hash table. It
inherits AbstractMap class and implements Map interface.
31
Java HashMap class
import java.util.*;
class HashMap1{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
System.out.println("Initial list of elements: "+hm);
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
hm.putIfAbsent(103, "Gaurav");
System.out.println("After invoking putIfAbsent() method ");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(104,"Ravi");
map.putAll(hm);
System.out.println("After invoking putAll() method ");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
} 32
Java TreeMap class
Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
⚫ Java TreeMap contains only unique elements.
⚫ Java TreeMap cannot have a null key but can have multiple null values.
33
Note on Comparator interface
34
Comparable interface
import java.util.*;
import java.io.*;
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
//Creating a test class to sort the elements
public class TestSort3{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
35
System.out.println(st.rollno+" "+st.name+" "+st.age);
Comparator
Student.java
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
AgeComparator.java
import java.util.*;
class AgeComparator implements
Comparator<Student>{
public int compare(Student s1,Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
} 36
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
return s1.name.compareTo(s2.name);
}
}
37
//Java Program to demonstrate the use of Java Comparator
import java.util.*;
import java.io.*;
class TestComparator{
public static void main(String args[]){
//Creating a list of students
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23)); Sorting by Name
al.add(new Student(106,"Ajay",27)); 106 Ajay 27
al.add(new Student(105,"Jai",21));
105 Jai 21
System.out.println("Sorting by Name"); 101 Vijay 23
//Using NameComparator to sort the elements
Collections.sort(al,new NameComparator());
//Traversing the elements of list Sorting by Age
for(Student st: al){ 105 Jai 21
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
101 Vijay 23
106 Ajay 27
System.out.println("sorting by Age");
//Using AgeComparator to sort the elements
Collections.sort(al,new AgeComparator());
//Travering the list again
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
} 38
39
40
Summary
41
QUE – 1: ArrayList
ASSIGNMENT
Create a class Book with below attributes:
int - id
String - title
double - price
int - pages
String - author
Make all the attributes private. Create corresponding getters
and setters.
Create a constructor which takes all parameters in the above
sequence. The constructor should set the value of attributes to
parameter values inside the constructor.
Create a class BookDemo with main method
42
ASSIGNMENT
searchBookById(ArrayList<Book> objList)
43
EXTRA ASSIGNMENTS
TOPIC: Map
The method displays all the elements in the map with the
key and value.
Call the above methods from the main method
44
Thank You