Why do we need Collections?
- A single variable that can hold multiple values is called an array. i. e. arrays are used to store group of elements (primitive type or object type) as a single entity. These elements are homogeneous and fixed number.
- The main advantage of array is we can represent multiple values with a single variable.
- Limitations of Arrays:love the morning koi Jimmy I’ll ok loo
- Arrays are fixed in size i. e. once we create an array with some size, there is no way we can increase or decrease its size based on our requirement. Hence, in order to use array, we need to know the size in advance which may not be possible always.
- Arrays can hold only homogeneous data type elements
Example
Student[] s = new Student[10000];
s[0] = new Student;(correct) but s[1] = new Customer(); (wrong)
We can resolve this problem by using object arrays.
Object [] o = new Object[1000];
o[0] = new Student();
o[1] = new Customer();
- There is no underlying data structure i.e. arrays do not support predefined methods. We have to write code explicitly, which is complexity of program. To overcome the above limitations of arrays we should go for collections.
Difference between Arrays and collections
Array
|
Collections
|
|
|
Collection | Collections |
|
|
Collections:
- It provides an architecture to store and manipulate a group of objects
- using java collections various operations can be performed on the data like searching, sorting, insertion, manipulation, deletion etc
- Java collection framework provides many interfaces and classes
Java Queue:
- Queue follows a FIFO approach i.e. it orders elements in first in first our manner
- The first element is removed first and last element removed in the last
- Version
- Heterogeneous data except TreeSet and TreeMap
- Duplicate add(e1), add(e2)
- Null inertion
- Insertion order e1, e2, e3 ..........e1, e2, e3
- Synchronized/non-synchronized
- Support predefined methods
- Coursers used to retrieve the data from collection class
Out of these 8 properties, 4 properties are common for List. These are
- Heterogeneous
- Null
- Duplicate
- Insertion
Note: In command line type this: javap java.util.Collection to see all the predefined methods in collections
Arrays are type safe:
int[] a = new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;
for (int aa: a){
System.out.printlln(aa);
}
Collections are not type safe:
Normal version:
ArrayList arrayList = new ArrayList( );
must use instanceof operator
must perform type casting
To provide the type safety to the collection use generics:
ArrayList <Emp> arrayList = new ArrayList<Emp>(); // only Emp
ArrayList <Student> arrayList = new ArrayList<Student>(); // only Student
Example I: Without generics
package com.cerotid.collection;
import java.util.ArrayList;
class Employee{
int eid;
String ename;
public Employee(int eid, String ename) {
this.eid = eid;
this.ename = ename;
// TODO Auto-generated constructor stub
}
}
class Student{
int sid;
String sname;
public Student(int sid, String sname) {
this.sid = sid;
this.sname = sname;
// TODO Auto-generated constructor stub
}
}
public class ArrayListDemo1 {
public static void main(String[] args) {
Employee e = new Employee(111, "Ratan");
Student s = new Student(222, "Anu");
ArrayList arrayList = new ArrayList();
arrayList.add(e);
arrayList.add(s);
arrayList.add(10);
arrayList.add("Ratan");
System.out.println(arrayList);
for (Object oo: arrayList) {
if(oo instanceof Employee) {
Employee ee = (Employee)oo;
System.out.println(ee.eid+"..."+ee.ename);
}
if(oo instanceof Student) {
Student ss = (Student)oo;
System.out.println(ss.sid+"..."+ss.sname);
}
if(oo instanceof Integer) {
System.out.println(oo);
}
if (oo instanceof String) {
System.out.println(oo);
}
}
}
}
Output:
[com.cerotid.collection.Employee@15db9742, com.cerotid.collection.Student@6d06d69c, 10, Ratan]
111...Ratan
222...Anu
10
Ratan
Example II: With generics....To provide type safety to the Collection
package com.cerotid.collection;
import java.util.ArrayList;
class Emp{
int eid;
String ename;
public Emp(int eid, String ename) {
this.eid = eid;
this.ename = ename;
// TODO Auto-generated constructor stub
}
}
public class ArrayListDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Emp e1 = new Emp(111, "Ratan");
Emp e2 = new Emp(222, "Anu");
Emp e3 = new Emp(333, "Aruna");
ArrayList<Emp> arrayList = new ArrayList<Emp>();
arrayList.add(e1);
arrayList.add(e2);
arrayList.add(e3);
for (Emp ee: arrayList) {
System.out.println(ee.eid + "..."+ee.ename);
}
}
}
Output:
111...Ratan
222...Anu
333...Aruna
Example III: ArrayList Concept:
package com.cerotid.collection;
import java.util.ArrayList;
public class ArrayListDemo3 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(10);
arrayList.add("Ratan");
arrayList.add("Durga");
arrayList.add(10.5);
System.out.println(arrayList);
arrayList.add(1, "Anu");
System.out.println(arrayList);
System.out.println(arrayList.size());
arrayList.remove(0);
System.out.println(arrayList);
arrayList.remove("Ratan");
System.out.println(arrayList);
System.out.println(arrayList.contains("Durga"));
System.out.println(arrayList.isEmpty());
arrayList.clear();
System.out.println(arrayList.isEmpty());
}
}
Output:
[10, Ratan, Durga, 10.5]
[10, Anu, Ratan, Durga, 10.5]
5
[Anu, Ratan, Durga, 10.5]
[Anu, Durga, 10.5]
true
false
true
Example IV:
package com.cerotid.collection;
import java.util.ArrayList;
public class ArrayListDemo4 {
public static void main(String[] args) {
Emp e1 = new Emp(111, "Ratan");
Emp e2 = new Emp (222, "Anu");
Emp e3 = new Emp(333, "Sajana");
Emp e4 = new Emp(444, "Aruna");
ArrayList<Emp> a1 = new ArrayList<Emp>();
a1.add(e1);
a1.add(e2);
ArrayList<Emp> a2 = new ArrayList<Emp>();
a2.addAll(a1);
a2.add(e3);
a2.add(e4);
System.out.println( "..........before removing e1..........");
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
a2.remove(e1);
System.out.println(".......after removing e1..............");
System.out.println(a2.contains(e1));
System.out.println(a2.containsAll(a1));
for (Emp ee: a2) {
System.out.println(ee.eid+"...."+ee.ename);
}
}
}
Output:
true
true
.......after removing e1..............
false
false
222....Anu
333....Sajana
444....Aruna
Example IV:Conversion of arrays into collection:
package com.cerotid.collection;
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListDemo6 {
public static void main(String[] args) {
String[] names = { "Ratan", "Anu", "Aruna" };
System.out.println("...output from arrays..........");
for (String name : names) {
System.out.println(name);
}
System.out.println("...conversion of arrays to into arraylist...before addition...");
ArrayList<String> list = new ArrayList<String>(Arrays.asList(names));
for (String str : list)
System.out.println(str);
System.out.println("........output from arraylist...after addition.....");
ArrayList<String> aList = new ArrayList<String>(Arrays.asList(names));
aList.add("aaa");
aList.add("bbb");
for (String str : aList) {
System.out.println(str);
}
System.out.println(".....output from arrayList ... after addition....");
ArrayList<String> arrList = new ArrayList<String>(Arrays.asList("Ratan", "Anu", "Aruna"));
arrList.add("ccc");
arrList.add("ddd");
for (String s1 : arrList)
System.out.println(s1);
}
}
Output:
...output from arrays..........
Ratan
Anu
Aruna
...conversion of arrays to into arraylist...before addition...
Ratan
Anu
Aruna
........output from arraylist...after addition.....
Ratan
Anu
Aruna
aaa
bbb
.....output from arrayList ... after addition....
Ratan
Anu
Aruna
ccc
ddd
Example V:Conversion of collection into arrays:
package com.cerotid.collection;
import java.util.ArrayList;
import java.util.List;
public class CollectionToArrayExample {
public static void main(String[] args) {
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Object[] objects = al.toArray();
// Printing array of objects
for (Object obj : objects)
System.out.println(obj);
// System.out.print(obj + " ");
}
}
Output:
10
20
30
40
Example VI:Conversion of collection into arrays:
package com.cerotid.collection;
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo7 {
public static void main(String[] args) {
List<String> aList = new ArrayList<String>();
aList.add("aaa");
aList.add("bbb");
aList.add("ccc");
aList.add("ddd");
Object[] objects = aList.toArray();
for (Object obj : objects) {
System.out.println(obj);
}
}
}
Output:
aaa
bbb
ccc
ddd
Example VII: Sort the data by using sort():
package com.cerotid.collection;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo8 {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
aList.add("Ratan");
aList.add("Anu");
aList.add("Aruna");
aList.add("Sravya");
System.out.println("......before sorting...........");
System.out.println(aList);
Collections.sort(aList);
System.out.println(".........after sorting........");
System.out.println(aList);
}
}
Output:
......before sorting...........
[Ratan, Anu, Aruna, Sravya]
.........after sorting........
[Anu, Aruna, Ratan, Sravya]
Example VII: Perform the sorting of Object in ArrayList (here Employee Object) using Comparable interface:
Important Notes:
- If you want to perform sorting, your data type must be homogeneous and class must implement comparable interface
- String class and all wrapper classes are internally implementing comparable interface and hence Collections.sort is possible
- But Employee class is not implementing comparable interface and we need to implement comparable interface in order to sort Employee
- javap java.lang.comparable has public abstract compareTo(); . This method compares two strings and returns integer value as a return value
- If two strings are equal, it returns zero, meaning no change
- If two Strings are not equal, it returns either positive or negative value. When positive, change will occur and when negative, no change.
- If comparable is not generic version, compareTo() is expecting object class, it performs type casting. However, for generic version, no need of type casting
package com.cerotid.collection;
import java.util.ArrayList;
import com.cerotid.ratanjavavideos.learning.Emp;
import java.util.*;
public class ArrayListDemo9 {
public static void main(String[] args) {
ArrayList<Emp> aList = new ArrayList<Emp>();
aList.add(new Emp(333, "Ratan"));
aList.add(new Emp(222, "Anu"));
aList.add(new Emp(111, "Durga"));
//Collections.sort(aList); impossible because Emp class is not implementing comparable interface
Collections.sort(aList);
for(Emp e: aList) {
System.out.println(e.eid+"...."+e.ename);
}
}
}
Case I: Sorting by using Emp id (integer data):
package com.cerotid.ratanjavavideos.learning;
public class Emp implements Comparable{
public int eid;
public String ename;
public Emp(int eid, String ename) {
this.eid = eid;
this.ename = ename;
}
public static void main(String[] args) {
}
@Override
public int compareTo(Object o) { //CompareTo is a object class, convert that object class to Emp type
Emp e = (Emp)o;
if (eid == e.eid ) {
return 0;
}
else if (eid>e.eid) {
return 1;
}
else {
return -1;
}
}
}
Output:
111....Durga
222....Anu
333....Ratan
Case II: Sorting by using Emp name (String data):
public class Emp implements Comparable{ // Here comparable is not generic
public int eid;
public String ename;
public Emp(int eid, String ename) {
this.eid = eid;
this.ename = ename;
}
public static void main(String[] args) {
}
/*public int compareTo(Object o) { //CompareTo is a object class, convert that object class to Emp type
Emp e = (Emp)o;
if (eid == e.eid ) { //for integer data this is the way
return 0;
}
else if (eid>e.eid) {
return 1;
}
else {
return -1;
}*/
public int compareTo(Object o) { //CompareTo is a object class, convert that object class to Emp type
Emp e = (Emp)o;
return ename.compareTo(e.ename); //if it is string data, directly use this method
}
}
Output:
222....Anu
111....Durga
333....Ratan
Case III: When you add -, it will sort in descending order:
public int compareTo(Object o) { //CompareTo is a object class, convert that object class to Emp type
Emp e = (Emp)o;
return -ename.compareTo(e.ename); //if it is string data, directly use this method
}
Output:
333....Ratan
111....Durga
222....Anu
When you add -, it will sort in descending order:
public class Emp implements Comparable<Emp>{
public int eid;
public String ename;
public Emp(int eid, String ename) {
this.eid = eid;
this.ename = ename;
}
public static void main(String[] args) {
}
public int compareTo(Emp e) { //CompareTo is a object class, convert that object class to Emp type
return -ename.compareTo(e.ename); //if it is string data, directly use this method
}
}
package com.cerotid.bank.model;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class CustomerReader {
//--declare customer storage bucket
private ArrayList<Customer> customerList = new ArrayList<>();
//--create method to read the file
public void readFile() throws IOException {
//find the file, open file
File file = new File("CustomerInput.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
//read line and
//loop through the lines until end of file
while ((line = bufferedReader.readLine()) != null) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(line.split(",")));
String firstName = list.get(1);
String lastName = list.get(0);
Customer customer = new Customer(firstName, lastName);
//store as single customer in the storage bucket
customerList.add(customer);
}
//close filereader
bufferedReader.close();
fileReader.close();
System.out.println("Contents of file:");
}
void printCustomerAccounts(){
//TODO print customer Accounts
}
//create writer file
public void writeFile() throws IOException {
//create file
File file = new File("CustomerSortedOutput.txt");
FileWriter filerWriter = new FileWriter(file);
//sortCustomers();
sortCustomersWithTheirLastNames();
BufferedWriter bufferedWriter = new BufferedWriter(filerWriter);
//write one by one in the file
for (Customer cust: customerList) {
bufferedWriter.write(cust.getFirstName());
bufferedWriter.write(" ");
bufferedWriter.write(cust.getLastName());
bufferedWriter.write("\n");
}
//close
bufferedWriter.close();
filerWriter.close();
}
/*private void sortCustomers() {
//TODO sort customer storage bucket in ascending order by their last name
ArrayList<String> lastNameList = new ArrayList<>();
for(Customer customer: customerList) {
lastNameList.add(customer.getLastName());
}
Object[] arr = (Object[]) lastNameList.toArray();
Arrays.sort(arr);
for(Object lastName: arr) {
System.out.println(lastName);
}
}*/
private void sortCustomersWithTheirLastNames() {
Collections.sort(customerList, new ComparatorConcept());
for (Customer cust: customerList) {
System.out.println(cust.getLastName());
}
}
}
Problems with comparable interface:
Problems with comparable interface:
- At a time, only one property sorting is possible
- we are mixing sorting logics with normal business logics
To overcome this problem, we are using comparator interface. This is customized sorting order.
Sorting the ArrayList data by using Comparator:
Advantage of Comparator interface:
- Multiple sorting at a time is possible
- We are separating sorting logics with business logics
To see methods available in Comparator interface, use javap java.util.comparator in command line prompt
- public abstract int compare(T, T)
- public abstract boolean equals(java.lang.object)
Employee id Comparator:
package com.cerotid.collection;
public class EidCom implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
if (e1.eid == e2.eid) {
return 0;
}
else if (e1.eid >e2.eid) {
return 1;
}
else {
return -1;
}
}
}
package com.cerotid.collection;
import java.util.*;
import java.util.*;
public class ArrayListDemo9 {
public static void main(String[] args) {
ArrayList<Emp> aList = new ArrayList<Emp>();
aList.add(new Emp(333, "Ratan"));
aList.add(new Emp(222, "Anu"));
aList.add(new Emp(111, "Durga"));
Collections.sort(aList, new EidComp());
for(Emp e: aList) {
System.out.println(e.eid+"...."+e.ename);
}
}
}
Output:
111....Durga
222....Anu
333....Ratan
Employee ename Comparator:
package com.cerotid.collection;
public class EnameComp implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Emp e1 = (Emp)o1;
Emp e2 = (Emp)o2;
return(e1.ename).compareTo(e2.ename);
}
}
package com.cerotid.collection;
import java.util.*;
import java.util.*;
public class ArrayListDemo9 {
public static void main(String[] args) {
ArrayList<Emp> aList = new ArrayList<Emp>();
aList.add(new Emp(333, "Ratan"));
aList.add(new Emp(222, "Anu"));
aList.add(new Emp(111, "Durga"));
Collections.sort(aList, new EnameComp());
for(Emp e: aList) {
System.out.println(e.eid+"...."+e.ename);
}
}
}
Output:
222....Anu
111....Durga
333....Ratan
Comparable | Comparator |
|
|
== operator | .equal() |
|
|
public class Test {
public static void main(String[] args) {
String s1 = new String("Durga");
String s2 = new String("Durga");
System.out.println(s1 == s2); //reference comparison, i.e. addresswise they are not equal
System.out.println(s1.equals(s2)); // content comparison
}
}
- .equals() method present in object class meant for reference comparison only based on our requirement we can override for content comparison
- In String class, all wrapper class and all collection classes, .equals() method is overridden for content comparison
When we have generic, we do not need to type cast:
Case I: Employee Eid Comparator:
package com.cerotid.collection;
public class EidComp implements Comparator<Emp>{
@Override
public int compare(Emp e1, Emp e2) {
if (e1.eid == e2.eid) {
return 0;
}
else if (e1.eid >e2.eid) {
return 1;
}
else {
return -1;
}
}
}
Case II: Employee Ename Comparator:
package com.cerotid.collection;
import java.util.*;
public class EnameComp implements Comparator<Emp>{
@Override
public int compare(Emp e1, Emp e2) {
return(e1.ename).compareTo(e2.ename);
}
}
9-key Interfaces of Collection Framework:
- Collection:
- If we want to represent a group of individual object as a single entity then we should go for collection
- Collection interface defines the most common methods which are applicable for any collection object
- In general, collection interface is considered as root interface of collection framework
- Note: there is no concrete class which implements collection interface directly
Difference between Collection and Collections
Collection | Collections |
|
|
- List Interface:
- List is child interface of collection
- If we want to represent a group of individual objects as a single entity where duplicates are allowed and insertion order is preserved then we should go for List
- We can differentiate duplicates by using index
- We can preserve insertion order by using index, hence index play very important role in list interface
ArrayList:
- The underline data structure is re-sizable or grow-able Array
- Duplicates are allowed
- Insertion order is preserved
- Heterogeneous objects are allowed ( except TreeSet and TreeMap everywhere heterogeneous objects are allowed)
- Null insertion is possible
- ArrayList and vector classes implements RandomAccess interface so that we can access any Random element with the same speed
- Hence if our frequent operation is retrieval operation then ArrayList is the best choice
ArrayList Constructors:
ArrayList arrayList = new ArrayList();
Creates an empty ArrayList object with default initial capacity 10. Once ArrayList reaches its map capacity a new ArrayList will be created with new capacity = (current capacity *3/2)+1.
RandomAccess Interface:
- Present in java.util.package
- It does not contain any methods and it is a Marker interface
ArrayList l1 = new ArrayList();
LinkedList l2 = new();
System.out.println(l1 instanceOf Serializable); //true
System.out.println(l2 instanceOf Cloneable); //true
System.out.println(l1 instanceOf RandomAccess); //true
System.out.println(l2 instanceOf RandomAccess); //false
ArrayList Uses:
- ArrayList is the best choice if our frequent operation is retrieval operation because ArrayList implements RandomAccess interface
- ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle because several shift operation are require
How to get synchronized version of ArrayList object?
- By default ArrayList object is non-synchronized but we can get synchronized version of ArrayList by using Collection class synchronizedList();
Non-Synchronized
ArrayList l1 = new ArrayList();
Synchronized
List l = Collections.synchronizedList(l1);
ArrayList | Vector |
|
|
ArrayList
|
LinkedList
|
|
|
LinkedList:
- The underlying data structure is Double Linked List
- Insertion order is preserved
- Duplicates are allowed
- Heterogeneous Objects are allowed
- Null insertion is possible
LinkedList Constructors:
LinkedList linkedList = new LinkedList();
Creates an empty LinkedList object
LinkedList linkedList = new LinkedList(Collection c);
Creates an equivalent LinkedList object for the given collection
Vector:
- The underlying data structure is resizable array or growable array
- Duplicate objects are allowed
- Insertion order is preserved
- Null inertion is possible
- Heterogeneous objects are allowed
- Vector class implements Serializable, Cloneable, and RandomAccess Interface
- Most of the methods present in vector are synchronized. Hence, vector object is thread safe
- Vector is the best choice if the frequent choice is retrieval
Constructors of Vector class
Vector v = new Vector();
Creates an empty vector object with default initial capacity 10, once vector reaches its maximum capacity a new vector object will be created with new capacity = 2*current capacity
Vector v = new Vector(int initialCapacity);
Creates an empty vector object with specified initial capacity
Vector v = new Vector(int initialCapacity, int incrementalCapacity);
Vector v = new Vector(Collection c);
Creates an equivalent vector object for the given collection
Stack:
- It is the child class of Vector
- It is specially designed class for Last in First out order (LIFO)
Methods in Stack:
Object push(Object obj);
For inserting an object to the stack
Object pop();
To remove and return top of the stack
Object peak();
To return the top of the stack without removal of object.
int search(Object obj);
If the specified object is available, it returns its offset from top of the stack.
If the object is not available, then it returns -1
Object pop();
For inserting an object to the stack
- Set Interface:
- Set is a child interface of collection
- If we want to represent a group of objects as a single entity, where duplicates are not allowed and insertion order is not preserved, then we should go for set interface.
- Set interface does not contain any new method and hence we have to use collection interface methods
HashSet: This class implements Set interface.
Points to Note about HashSet:
- HashSet doesn’t maintain any order, the elements would be returned in any random order.
- Duplicates are not allowed. If you try to add a duplicate element in HashSet, the old value would be overwritten.
- Null inertion is possible, however, if you insert more than one null, it would still return only one null value.
- HashSet is non-synchronized.
- The iterator returned by this class is fail-fast which means iterator would throw ConcurrentModificationException if HashSet has been modified after creation of iterator, by any means except iterator’s own remove method.
- HashSet is the best choice, if our frequent operation is Search operation.
Constructors of HashSet:
HashSet h = new HashSet();
Creates an empty HashSet object with default initial capacity 16 and default Fill Ratio 0.75
HashSet h = new HashSet(int initialCapacity)
creates an empty HashSet object with specified initial capacity and default fill ratio 0.75
HashSet h = new HashSet(int initialCapacity, float loadFactor);
Creates an empty HashSet object with specified initial capacity and specified load factor (or Fill Ratio)
HashSet h = new HashSet(Collection c)
for interior conversion between collection objects
Note for Load Factor or Fill Ratio: After loading the loading the factor, a new HashSet object will be created, that factor is called load factor or fill ratio.
HashSet Example:
public class HashSetConcept {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Rakesh");
set.add("Rakesh");
set.add("David");
set.add("Sunil");
set.add("Sanjiv");
set.add("4");
//Can add null element as well
set.add(null);
set.add(null);
System.out.println(set);
}
}
Output:
[null, 4, Sunil, Rakesh, David, Sanjiv]
- SortedSet:
- It is the child interface of set
- If we want to represent a group of individual objects according some sorting order and duplicates are not allowed, then we should go for sortedSet.
- NavigableSet:
- It is the child interface of SortedSet. It defines several methods for navigation purposes. TreeSet is the implementation class.
TreeSet:
- Inertion order is not preserved, but all objects will be inserted according to some sorting order
- TreeSet allows null element but only once
- Duplicate objects are not allowed
- The underlying data structure is Balanced Tree
- Heterogeneous objects are not allowed. If we are trying to insert heterogeneous objects then we will get runtime exception saying ClassCastException
TreeSet Constructors:
TreeSet t = new TreeSet();
Creates an empty TreeSet object, where elements will be inserted according to default natural sorting order
TreeSet t = new TreeSet(Comparator c);
Creates an empty TreeSet object, where elements will be inserted according to customized sorting order
TreeSet t = new TreeSet(Collection c);
collection to TreeSet
TreeSet t = new TreeSet(SortedSet s);
Null Acceptance:
- For empty TreeSet, first element null inertion is possible. But after inserting that null if we are trying to insert any another element, we will get NullPointerException.
- For non empty TreeSet, if we are trying to inset null then, we will get NullPointerException
Example of TreeSet:
package com.cerotid.collections;
import java.util.TreeSet;
public class TreeSetConcept {
public static void main(String[] args) {
//Adding elements to TreeSet<String>
TreeSet<String> set1 = new TreeSet<String>();
set1.add("Rakesh");
set1.add("Rakesh");
set1.add("David");
set1.add("Sunil");
set1.add("Sanjiv");
//Displaying TreeSet
System.out.println(set1);
//Adding elements to TreeSet<String>
TreeSet<Integer> set2 = new TreeSet<Integer>();
set2.add(0);
set2.add(5);
set2.add(12);
set2.add(8);
set2.add(3);
System.out.println(set2);
}
}
Output:
[David, Rakesh, Sanjiv, Sunil]
[0, 3, 5, 8, 12]
LinkedHashSet:
LinkedHashSet (child class of HashSet) is similar to the HashSet except the below mentioned differences:
HashSet
|
LinkedHashSet
|
|
|
Note: LinkedHashSet is the best choice to develop cache based applications, where duplicates are not allowed and inertion order must be preserved
Examples of LinkedHashSet:
Example I:
import java.util.LinkedHashSet;public class LinkedHashSetExample {
public static void main(String args[]) {
// LinkedHashSet of String Type
LinkedHashSet<String> lhset = new LinkedHashSet<String>();
// Adding elements to the LinkedHashSet
lhset.add("Z");
lhset.add("PQ");
lhset.add("N");
lhset.add("O");
lhset.add("KK");
lhset.add("FGH");
System.out.println(lhset);
// LinkedHashSet of Integer Type
LinkedHashSet<Integer> lhset2 = new LinkedHashSet<Integer>();
// Adding elements
lhset2.add(99);
lhset2.add(7);
lhset2.add(0);
lhset2.add(67);
lhset2.add(89);
lhset2.add(66);
System.out.println(lhset2);
}}
Output:
[Z, PQ, N, O, KK, FGH]
[99, 7, 0, 67, 89, 66]
Observe the output: Both types of LinkedHashSet have preserved the insertion order.
Example II:
package com.cerotid.collections;
import java.util.LinkedHashSet;
import java.util.TreeSet;
public class LinkedHashSetConcept {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
linkedHashSet.add("Rakesh");
linkedHashSet.add("Rakesh");
linkedHashSet.add("David");
linkedHashSet.add("Sunil");
linkedHashSet.add("Sanjiv");
//Can add null element as well
//set.add(null);
//set.add(null);
System.out.println(linkedHashSet);
//Converting LinkedHashSet to TreeSet
TreeSet<String> tset = new TreeSet<>(linkedHashSet);
System.out.println(tset);
}
}
Output:
[Rakesh, David, Sunil, Sanjiv]
[David, Rakesh, Sanjiv, Sunil]
LinkedList
Example of LinkedList in Java
import java.util.*;public class LinkedListExample {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
/*add(String Element) is used for adding
* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");
/*Display Linked List Content*/
System.out.println("Linked List Content: " +linkedlist);
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: " +linkedlist);
/*This is how to get and set Values*/
Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set method: " +firstvar2);
/*Remove first and last element*/
linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
/* Add to a Position and remove from a position*/
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}}
Output:
Linked List Content: [Item1, Item5, Item3, Item6, Item2]LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item]First element: First ItemFirst element after update by set method: Changed first item
LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2]Final Content: [Newly added item, Item1, Item3, Item6, Item2]
Map: It is used to store two objects; key object and value object.
List | Set |
|
|
- Queue Interface:
- It is the child interface of collection.
- If we want to represent a group of individual objects prior to processing then we should go for Queue
- EX: before sending email all email ids we need to store somewhere and in which order we saved in the same order email should be delivered (First in First Out). For this requirement, Queue is the best choice.
Example:
Before sending a mail, all mail id's we have to store somewhere and in which we saved in the same order mail's should be delivered (first in first out) for this requirement, Queue concept is the best choice
Notes:
- All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, and Queue) meant for representing a group of individual objects.
- If we want to represent a group of objects as key value pairs then we should go for Map interface
- Map Interface:
- The map interface maps unique keys to values. A key is an object that you use to retrieve a value at later date. Given a key and a value you can store the value in a map object. After the value is stored, you can retrieve it by using its key.
- Map is not the child interface of Collection.
- If we want to represent a group of individual objects as key value pairs then we should go for Map.
- Both key and value are objects, duplicated keys are not allowed but values can be duplicate.
- SortedMap Interface:
- It is the child interface of Map
- If we want to represent group of key value pairs according to some sorting order of keys then we should go for SortedMap
- NavigableMap:
- It is the child interface of SortedMap, it defines several utility methods for navigation purpose
- TreeMpa is the implementation class.
Note:
- Collection Interface: collection interface doesn't contain any method to retrieve objects.
- There is no concrete class which implements collection interface directly.
Three Cursors of Java
- If we want to retrieve objects one by one from collection, then we should go for Cursors
- There are three types of Cursors available in java
- Enumeration
- Iterator
- ListIterator
Two utility class:
- Collections
- Arrays
Enumeration:
- Introduced in 1.0 version (for legacy)
- We can use Enumeration to get Object one by one from the old collection objects (Legacy Collections)
- We can create Enumeration object by using elements() method of Vector class
public Enumeration elements();
Example:
Enumeration e = v.elements();
Methods of Enumeration:
Enumeration defines the following two methods
public boolean hasMoreElelments();
public Object nextElement();
Example:
import java.util.Enumeration;
public class EnumerationDemo {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 0; i<=10; i++) {
v.addElement(i);
}
System.out.println(v); //[0, 1, 2, .............10]
Enumeration e = v.elements();
while(e.hasMoreElements()) {
Integer I = (Integer)e.nextElement();
if (I%2 ==0) {
System.out.println(I); //[0, 2, ..............,10]
}
}
System.out.println(v); //[0, 1, 2, ............10]
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
2
4
6
8
10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Limitations of Enumeration:
- Enumeration concept is applicable only for legacy classes and hence it it not a universal cursor.
- By using Enumeration, we can get only read access and we can not perform remove operation
- To overcome above limitations of Enumeration, we should go for Iterator
Iterator:
- We can apply Iterator concept for any Collection object, hence it is universal cursor.
- By using Iterator, we can perform both read and remove operations.
- We can create Iterator object by using iterator() method of Collection interface
public Iterator iterator();
Example:
Iterator itr = C.iterator();
where C is any Collection object
Methods of Iterator:
public boolean hasNext();
public Object next();
public void remove();
Example of Iterator:
package com.cerotid.cursorsconcept;
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList I = new ArrayList();
for (int i = 0; i<= 10; i++) {
I.add(i);
}
System.out.println(I); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator itr = I.iterator();
while(itr.hasNext()) {
Integer n = (Integer)itr.next();
if(n%2==0) {
System.out.println(n);
}
else {
itr.remove();
}
}
System.out.println(I);
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
2
4
6
8
10
[0, 2, 4, 6, 8, 10]
Limitations of Iterator:
- By using Enumeration and Iterator, we can move to forward direction only and we can move towards backward direction, hence these are single direction cursors.
- By using Iterator, we can perform only read and remove operations and we can not perform replacement of new objects.
- To overcome these limitations, we should go for ListIterator.
ListIterator:
- By using ListIterator, we can move either to the forward direction or to the backward direction, hence ListIterator is bidirectional cursor
- By using ListIterator, we can perform replacement and addition of new objects in addition to read and remove operations
- We can create ListIterator Object by using listIterator() method of List interface
public ListIterator listIterator()
Example:
ListIterator itr = I.listIterator();
where I is any List object
Example of ListIterator:
package com.cerotid.cursorsconcept;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListIntertorDemo {
public static void main(String[] args) {
LinkedList I = new LinkedList();
I.add("Balkrishna");
I.add("Hemkanti");
I.add("Ram");
I.add("Babita");
System.out.println(I); //[Balkrishna, Hemkanti, Ram, Babita]
ListIterator itr = I.listIterator();
while(itr.hasNext()) {
String s = (String)itr.next();
if(s.equals("Hemkanti")) {
itr.remove();
}
else if(s.equals("Babita")) {
itr.add("Aayushi");
}
else if (s.equals("Ram")) {
itr.set("Hari");
}
}
System.out.println(I); //[Balkrishna, Hari, Babita, Aayushi]
}
}
Output:
[Balkrishna, Hemkanti, Ram, Babita]
[Balkrishna, Hari, Babita, Aayushi]
Property | Enumeration | Iterator | ListIterator |
Applicable for | only legacy classes | Any Collection classes | only List classes |
Movement | only forward direction | only forward direction | both forward and backward direction |
Accessibility | only read access | both read and remove | read, remove, replace and addition of new objects |
How to get it? | by using element() method of vector class | by using iterator() method of Collection interface | by using listIterator() method of List interface |
Methods |
2 methods:
hasMoreElements()
nextElement()
|
3 methods:
hasNext()
next()
remove()
| 9 methods |
is it legacy? | yes (1.0 version) | No (1.2 version) | No (1.2 version) |
No comments:
Post a Comment