Collections & ArrayList_
Collections & ArrayList_
6
TCS
The Collection interface – basic operations
• Basic operations in collection interface:
add(object): this method used to add an object to
collection.
int size(): returns the number of elements in the
collection
equals(Object o): compares the specified object with
this collection for equality
• boolean isEmpty(): checks if a collection is empty
• boolean contains(Object element): checks
whether a given object is present in the collection
8
Collection : Root interface with basic methods like add(), remove(),
contains(), isEmpty(), addAll(), ... etc.
9
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
TreeMa
p
Map HashMap (sorted LinkedHashMap
)
12
TCS
public interface List<E> extends Collection
<E>
Use java.util.list package to implement list
To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
13
public interface List<E> extends Collection
<E>
// 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
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
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] 17
Is arraylist empty? false TCS
A sample code using ArrayList
import java.util.*;
class Company
{
ArrayList<Employee> employeeRegister = new ArrayList<Employee>();
class Employee
{
private String empNo; Company techSmart = new Company()
private String name; Employee emp1 = new Employee("121","Bob")
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
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.
can contain duplicate elements.
Null insertion is possible
maintains insertion order.
is non synchronized.
Hetrogenous objects are allowed
manipulation is fast because no shifting needs to occur.
Best for frequent insertion and deletion in middle
20
public interface Set<E>
extends Collection<E>
21
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);
}
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.
contains unique elements only.
allows null value.
doesn't maintain the insertion order. Here, elements are inserted on the basis of their
hashcode.
is the best approach for search operations.
Heterogenous allowed
Best for searching due to hashcode alogorithm
23
HashSet
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
LinkedHashSet
25
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.
26
public interface Map<K,V>
27
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());
}
} 29
}
Java HashMap class
Java HashMap class implements the map interface by using a hash table. It
inherits AbstractMap class and implements Map interface.
contains values based on the key.
contains only unique keys.
allows null key or value.
is non synchronized.
maintains no order.
30
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());
}
}
} 31
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.
Java TreeMap is non synchronized.
Java TreeMap maintains ascending order.
32
Note on Comparator interface
33
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){
34
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;
} 35
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
return s1.name.compareTo(s2.name);
}
}
36
//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);
} 37
38
Summary
Collections framework makes data processing and
manipulation easier.
39
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
40
ASSIGNMENT
searchBookById(ArrayList<Book> objList)
This method will take Array List of Book objects and id as input
and returns the position of the id if found or -1 if not found.
41
EXTRA ASSIGNMENTS
TOPIC: Map
The method adds the id of the input object as the key to the
map and the input object as the value for the same.
The method displays all the elements in the map with the
key and value.
Call the above methods from the main method
42
Thank You