Professional Documents
Culture Documents
Java Training Material v1.0 - Day 2
Java Training Material v1.0 - Day 2
Java Training Material v1.0 - Day 2
Java
Collection in JAVA – Day 2
Version: 1.0
Last Modified On: Jun 02 / 2016
1
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
Table of Contents
1. JAVA COLLECTIONS ............................................................................................4
2. ARRAYLIST CLASS ..............................................................................................5
2.1. Java ArrayList class ...................................................................................................5
2.2. Java Non-generic Vs Generic Collection.........................................................................5
2.3. Two ways to iterate the elements of collection in java .....................................................6
2.3.1. Iterating the elements of Collection by iterator interface ........................................................ 6
3
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
1. JAVA COLLECTIONS
Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.
All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
4
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
2. ARRAYLIST CLASS
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.
5
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
Ajay
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example
to traverse ArrayList elements using for-each loop.
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
for(String obj:al)
System.out.println(obj);
}
}
Ravi
Vijay
6
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
Ravi
Ajay
import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
7
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
al.addAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ajay
Sonoo
Hanumat
al.removeAll(al2);
}
}
iterating the elements after removing the elements of al2...
Vijay
Ajay
8
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
9
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
3. LINKEDLIST CLASS
o Java LinkedList class uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
10
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
4. ARRAYLIST VS LINKEDLIST
ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non-synchronized classes.
But there are many differences between ArrayList and LinkedList classes that are given below.
ArrayList LinkedList
ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to store
store the elements. the elements.
Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than ArrayList
it internally uses array. If any element is because it uses doubly linked list so no bit shifting is
removed from the array, all the bits are required in memory.
shifted in memory.
ArrayList class can act as a list only LinkedList class can act as a list and queue both
because it implements List only. because it implements List and Deque interfaces.
ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
import java.util.*;
class TestArrayLinked{
public static void main(String args[]){
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
11
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
12
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
5. LISTITERATOR INTERFACE
List Interface is the subinterface of Collection. It contains methods to insert and delete
elements in index basis. It is a factory of ListIterator interface.
ListIterator Interface is used to traverse the element in backward and forward direction.
ListIterator<String> itr=al.listIterator();
14
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
6. HASHSET CLASS
o Uses hashtable to store the elements. It extends AbstractSet class and implements
Set interface.
o Contains unique elements only.
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
15
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
}
}
Output:Ajay
Vijay
Ravi
16
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
7. HASHMAP CLASS
o A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:102 Rahul
100 Amit
101 Vijay
17
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
8. HASHTABLE CLASS
o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key. It implements the Map interface and extends Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
Example of Hashtable:
import java.util.*;
class TestCollection16{
public static void main(String args[]){
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());
}
}
}
18
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap Hashtable
HashMap allows one null key and multiple null Hashtable doesn't allow any null key or
values. value.
We can make the HashMap as synchronized by Hashtable is internally synchronized and can't
calling this code be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
19
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
10.1. Inheritance
10.2. Interface
10.3. Abstract
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
20
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
10.4.2. Try
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
21
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
The code which is prone to exceptions is placed in the try block, when an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example:
Here is code segment showing how to use multiple try/catch statements.
try
23
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
24
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
...
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
25
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares that
it throws a RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
26
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
1. Java throw keyword is used to Java throws keyword is used to declare an exception.
explicitly throw an exception.
4. Throw is used within the Throws is used with the method signature.
method.
5. You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws IOException,SQLException.
27
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
The try-with-resources
Generally when we use any resources like streams, connections etc... We have to close them
explicitly using finally block. In the program given below we are reading data from a file using
FileReader and we are closing it using finally block.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]){
29
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
FileReader fr=null;
try{
File file=new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();
}
finally{
try{
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
try-with-resources, also referred as automatic resource management is a new
exception handling mechanism that was introduced in Java7, which automatically closes the
resources used within the try catch block.
To use this statement you simply need to declare the required resources within the
parenthesis, the created resource will be closed automatically at the end of the block, below
given is the syntax of try-with-resources statement.
Below given is the program that reads the data in a file using try-with-resources statement.
import java.io.FileReader;
import java.io.IOException;
30
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
}
}
}
Following points are to be kept in mind while working with try-with resources statement.
while you declare multiple classes in the try block of try-with-resources statement these
classes are closed in reverse order.
Except the deceleration of resources within the parenthesis every thing is same as normal
try/catch block of a try block.
The resource declared in try gets instantiated just before the start of the try-block.
31
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
You just need to extend the predefined Exception class to create your own Exception. These
are considered to be checked exceptions. The following InsufficientFundsException class
is a user-defined exception that extends the Exception class, making it a checked exception.
An exception class is like any other class, containing useful fields and methods.
Example:
32
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
try
{
33
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
34
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,
Programmatic exceptions: - These exceptions are thrown explicitly by the application or the
API programmers Examples: IllegalArgumentException, IllegalStateException.
35
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
Suggestion: If you are beginner to java, lookup only two usage of this keyword.
36
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
11.1.2. The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves
the problem of ambiguity.
class Student10{
int id;
String name;
Output:
0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that
is why we are using this keyword to distinguish between local variable and instance variable.
Output
111 Karan
222 Aryan
If local variables (formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:
38
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to
reuse that constructor.
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
class Student14{
int id;
String name;
String city;
39
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
Output:
111 Karan null
222 Aryan delhi
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}
40
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}
41
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
11.1.4. The this keyword can be used to invoke current class method
(implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
42
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
Output:method is invoked
43
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
11.1.6. The this keyword can be passed as argument in the constructor call.
We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10
44
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
11.1.7. The this keyword can be used to return current class instance.
We can return the this keyword as an statement from the method. In such case, return type
of the method must be the class type (non-primitive). Let's see the example:
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
obj.m();
}
}
output:A5@22b3ea59
A5@22b3ea59
45
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
46
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
Output: 50
47
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The super keyword can also be used to invoke the parent class constructor as given below:
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
}
}
Output: Vehicle is created
Bike is created
As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement. If you are creating your own constructor and you don't
have either this() or super() as the first statement, compiler will provide super() as the first
statement of the constructor.
48
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
49
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:
class Person{
void message(){System.out.println("welcome");}
}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not
of Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class does
not have message() method, so you can directly call message() method.
50
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
void display(){
message();//will invoke parent class message() method
}
51
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2
52
Cognizant Proprietary Information – CONFIDENTIAL