0% found this document useful (0 votes)
6 views

Collections in Java UNIT 4.1

Java volume 4

Uploaded by

sirilkanuri01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Collections in Java UNIT 4.1

Java volume 4

Uploaded by

sirilkanuri01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Collections in Java

1. Java Collection Framework


2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is an optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

Method Description

public boolean add(E e) It is used to insert an element in this collection.

public boolean It is used to insert the specified collection


addAll(Collection<? extends elements in the invoking collection.
E> c)

public boolean It is used to delete an element from the collection.


remove(Object element)

public boolean It is used to delete all the elements of the specified collection from
removeAll(Collection<?> c) the invoking collection.

default boolean It is used to delete all the elements of the collection that
removeIf(Predicate<? super satisfy the specified predicate.
E> filter)

public boolean It is used to delete all the elements of invoking collection


retainAll(Collection<?> c) except the specified collection.

public int size() It returns the total number of elements in the collection.

public void clear() It removes the total number of elements from the collection.

public boolean It is used to search an element.


contains(Object element)

public boolean It is used to search the specified collection in the collection.


containsAll(Collection<?> c)

public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.

2 public Object next() It returns the element and moves the cursor pointer to
the next element.

3 public void remove() It removes the last elements returned by the iterator.
It is less used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface
extends the Iterable interface and therefore all the subclasses of Collection interface also
implement the Iterable interface.

Iterator<T> iterator()

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection
framework. It declares the methods that every collection will have. In other words, we can say
that the Collection interface builds the foundation on which the collection framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();
Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any
element is removed from the array list.

Hierarchy of ArrayList class


As shown in the above diagram, Java ArrayList class extends AbstractList class which implements
List interface. The List interface extends the Collection and Iterable interfaces in hierarchical
order.
ArrayList class declaration
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }

Constructors of Java ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized


with the elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the


specified
initial capacity.

Methods of Java ArrayList

Method Description

void add(int index, E It is used to insert the specified element at the specified position in a
element) list.
boolean add(E e) It is used to append the specified element at the end of a list.

boolean It is used to append all of the elements in the specified collection to the
addAll(Collection<? end of this list, in the order that they are returned by the specified
extends E> c) collection's iterator.

boolean It returns true if the list contains the specified element


contains(Object o)

E set(int index, E It is used to replace the specified element in the list,


element) present at the specified position.

void It is used to sort the elements of the list on the basis of specified
sort(Comparator<? comparator.
super E> c)

int size() It is used to return the number of elements present in the list.

---------------------------------------------------------------------------------------------------------------------

LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.

1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:

Ravi
Vijay
Ravi
Ajay

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides its methods like boolean
push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Java List Interface


List Interface is the subinterface of Collection. It contains index-based methods to insert and
delete elements. It is a factory of ListIterator interface.
List Interface declaration
1. public interface List<E> extends Collection<E>

Methods of Java List Interface

**Same methods as above…

Java List Example


1. import java.util.*;
2. public class ListExample{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("An element at 2nd position: "+al.get(2));
10. for(String s:al){
11. System.out.println(s);
12. }
13. }
14. }

Output:

An element at 2nd position: Vijay


Amit
Sachin
Vijay
Kumar

Java ListIterator Interface


ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration


1. public interface ListIterator<E> extends Iterator<E>
Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean hasNext() This method returns true if the list iterator has more elements
while traversing the list in the forward direction.

E next() This method returns the next element in the list and advances the
cursor position.

int nextIndex() This method returns the index of the element that would be returned
by a subsequent call to next()

boolean hasPrevious() This method returns true if this list iterator has more elements while
traversing the list in the reverse direction.

E previous() This method returns the previous element in the list and moves the
cursor position backward.

E previousIndex() This method returns the index of the element that would be returned
by a subsequent call to previous().

void remove() This method removes the last element from the list that was returned
by next() or previous() methods

void set(E e) This method replaces the last element returned by next() or
previous() methods with the specified element.

Example of ListIterator Interface


1. import java.util.*;
2. public class ListIteratorExample1{
3. public static void main(String args[]){
4. List<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. ListIterator<String> itr=al.listIterator();
10. System.out.println("Traversing elements in forward direction");
11. while(itr.hasNext()){
12.
13. System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
14. }
15. System.out.println("Traversing elements in backward direction");
16. while(itr.hasPrevious()){
17.
18. System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
19. }
20. }
21. }

Output:

Traversing elements in forward direction


index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

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.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class


The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.
Constructors of Java HashSet class

SN Constructor Description

1) HashSet() It is used to construct a default HashSet.

2) HashSet(int capacity) It is used to initialize the capacity of the hash


set to the given integer value capacity.
The capacity grows automatically as elements are
added to the HashSet.

3) HashSet(int capacity, float It is used to initialize the capacity of the hash set
loadFactor) to the given integer value capacity and the
specified load factor.

4) HashSet(Collection<? extends E> c) It is used to initialize the hash set by


using the elements of the collection c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

SN Modifier & Method Description


Type

1) boolean add(E e) It is used to add the specified element to this


set if it is not already present.

2) void clear() It is used to remove all of the elements from


the set.

3) object clone() It is used to return a shallow copy of this HashSet


instance: the elements themselves are not cloned.

4) boolean contains(Object o) It is used to return true if this set contains the


specified element.
5) boolean isEmpty() It is used to return true if this set contains no
elements.

6) Iterator<E iterator() It is used to return an iterator over the elements in


> this set.

7) boolean remove(Object o) It is used to remove the specified element from this


set if it is present.

8) int size() It is used to return the number of elements in


the set.

9) Spliterator spliterator() It is used to create a late-binding and fail-fast


<E> Spliterator over the elements in the set.

Java 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.

The important points about Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.

Hierarchy of TreeSet class


As shown in the above diagram, Java TreeSet class implements the NavigableSet interface. The
NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical
order.
TreeSet class declaration
Let's see the declaration for java.util.TreeSet class.

1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, S


erializable

Constructors of Java TreeSet class

Constructor Description

TreeSet() It is used to construct an empty tree set that will be


sorted in ascending order according to the
natural order of the tree set.

TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the
elements of the collection c.

TreeSet(Comparator<? super E> It is used to construct an empty tree set that


comparator) will be sorted according to given comparator.

TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the


elements of the given SortedSet.

Methods of Java TreeSet class

Method Description

boolean add(E e) It is used to add the specified element to this


set if it is not already present.

boolean addAll(Collection<? It is used to add all of the elements in the specified


extends E> c) collection to this set.

E ceiling(E e) It returns the equal or closest greatest element of the


specified element from the set, or null there is no such
element.

Comparator<? super E> It returns comparator that arranged elements in order.


comparator()

Iterator iterator() It is used to iterate the elements in ascending order.

boolean contains(Object o) It returns true if this set contains the specified element.

boolean isEmpty() It returns true if this set contains no elements.

E first() It returns the first (lowest) element currently in this sorted set.

E last() It returns the last (highest) element currently in this sorted set.

int size() It returns the number of elements in this set.

Java TreeSet Examples

Java TreeSet Example 1:


Let's see a simple example of Java TreeSet.

1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ajay
Ravi
Vijay
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element
is removed first and last element is removed at last.

Queue Interface declaration


1. public interface Queue<E> extends Collection<E>

Methods of Java Queue Interface

Method Description

boolean add(object) It is used to insert the specified element into this queue and
return true upon success.

boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or
returns null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue,
or returns null if this queue is empty.

PriorityQueue class
The PriorityQueue class provides the facility of using queue. But it does not orders the elements
in FIFO manner. It inherits AbstractQueue class.

PriorityQueue class declaration


Let's see the declaration for java.util.PriorityQueue class.

1. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable


Java PriorityQueue Example
1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit");
6. queue.add("Vijay");
7. queue.add("Karan");
8. queue.add("Jai");
9. queue.add("Rahul");
10. System.out.println("head:"+queue.element());
11. System.out.println("head:"+queue.peek());
12. System.out.println("iterating the queue elements:");
13. Iterator itr=queue.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. queue.remove();
18. queue.poll();
19. System.out.println("after removing two elements:");
20. Iterator<String> itr2=queue.iterator();
21. while(itr2.hasNext()){
22. System.out.println(itr2.next());
23. }
24. }
25. }
Test it Now
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay

Java Deque Interface


Java Deque Interface is a linear collection that supports element insertion and removal at both
ends. Deque is an acronym for "double ended queue".
Deque Interface declaration
1. public interface Deque<E> extends Queue<E>

Methods of Java Deque Interface

Method Description

boolean add(object) It is used to insert the specified element into this deque
and return true upon success.

boolean offer(object) It is used to insert the specified element into this deque.

Object remove() It is used to retrieves and removes the head of this deque.

Object poll() It is used to retrieves and removes the head of this deque,
or returns null if this deque is empty.

Object element() It is used to retrieves, but does not remove, the head of this deque.

Object peek() It is used to retrieves, but does not remove, the head of this deque,
or returns null if this deque is empty.

ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.

The important points about ArrayDeque class are:

o Unlike Queue, we can add or remove elements from both sides.


o Null elements are not allowed in the ArrayDeque.
o ArrayDeque is not thread safe, in the absence of external synchronization.
o ArrayDeque has no capacity restrictions.
o ArrayDeque is faster than LinkedList and Stack.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.

ArrayDeque class declaration


Let's see the declaration for java.util.ArrayDeque class.

1. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneabl


e, Serializable

Java ArrayDeque Example


1. import java.util.*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Ravi");
7. deque.add("Vijay");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

Java Comparator interface


Java Comparator interface is used to order the objects of a user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).

It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member, for example, rollno, name, age or anything else.
Methods of Java Comparator Interface

Method Description

public int compare(Object obj1, Object It compares the first object with the second object.
obj2)

public boolean equals(Object obj) It is used to compare the current object with
the specified object.

public boolean equals(Object obj) It is used to compare the current object with
the specified object.

Collections class
Collections class provides static methods for sorting the elements of a collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type
elements also.

Method of Collections class for sorting List elements


public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

Java Comparator Example (Non-generic Old Style)


Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:

1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java

Student.java

This class contains three fields rollno, name and age and a parameterized constructor.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java

This class defines comparison logic based on the age. If the age of the first object is greater than
the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age of the
first object is less than the second object, we are returning a negative value, it can be any
negative value, and if the age of both objects is equal, we are returning 0.

1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("Sorting by age");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparator Example (Generic)


Student.java
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }
NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
Simple.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("Sorting by age");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24. }
25. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27

Properties class in Java


The properties object contains key and value pair both as a string. The java.util.Properties class
is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class provides
methods to get data from the properties file and store data into the properties file. Moreover, it
can be used to get the properties of a system.

An Advantage of the properties file


Recompilation is not required if the information is changed from a properties file: If any
information is changed from the properties file, you don't need to recompile the java class. It is
used to store information which is to be changed frequently.

Constructors of Properties class

Method Description

Properties() It creates an empty property list with no default values.

Properties(Properties defaults) It creates an empty property list with the specified defaults.

Methods of Properties class


The commonly used methods of Properties class are given below.

Method Description

public void load(Reader r) It loads data from the Reader object.

public void load(InputStream is) It loads data from the InputStream object

public void It is used to load all of the properties


loadFromXML(InputStream in) represented by the XML document on
the specified input stream into this
properties table.

public String getProperty(String key) It returns value based on the key.

public String getProperty(String key, It searches for the property with the
String defaultValue) specified key.
public void setProperty(String key, It calls the put method of Hashtable.
String value)

public void list(PrintStream out) It is used to print the property list out to the specified
output stream.

public void list(PrintWriter out)) It is used to print the property list out to the specified
output stream.

public Enumeration<?> It returns an enumeration of all the keys from the


propertyNames()) property list.

public Set<String> It returns a set of keys in from property list where the
stringPropertyNames() key and its corresponding value are strings.

public void store(Writer w, String It writes the properties in the writer object.
comment)

public void store(OutputStream os, It writes the properties in the OutputStream object.
String comment)

public void It writes the properties in the writer object for


storeToXML(OutputStream os, String generating XML document.
comment)

public void storeToXML(Writer w, It writes the properties in the writer object for
String comment, String encoding) generating XML document with the specified encoding.

Example of Properties class to get information from the properties


file
To get information from the properties file, create the properties file first.

db.properties
1. user=system
2. password=oracle

Now, let's create the java class to read the data from the properties file.

Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle

Now if you change the value of the properties file, you don't need to recompile the java class.
That means no maintenance problem.

Example of Properties class to get all the system properties


By System.getProperties() method we can get all the properties of the system. Let's create the
class that gets information from the system properties.

Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........

Java Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.

Points to remember
o 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.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Se


rializable

Hashtable class Parameters


Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.
Constructors of Java Hashtable class

Constructor Description

Hashtable() It creates an empty hashtable having the initial


default capacity and load factor.

Hashtable(int capacity) It accepts an integer parameter and creates


a hash table that contains a specified initial capacity.

Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified i
loadFactor.

Hashtable(Map<? extends K,? extends It creates a new hash table with the same
V> t) mappings as the given Map.

Methods of Java Hashtable class

Method Description

void clear() It is used to reset the hash table.

Object clone() It returns a shallow copy of the Hashtable.

Enumeration elements() It returns an enumeration of the values in the hash table.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super It performs the given action for each entry in the map until
K,? super V> action) all entries have been processed or the action throws an
exception.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
defaultValue) map contains no mapping for the key.

int hashCode() It returns the hash code value for the Map
Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.

Set<K> keySet() It returns a Set view of the keys contained in the map.

V put(K key, V value) It inserts the specified value with the specified key in the
hash table.

void putAll(Map<? extends K,? It is used to copy all the key-value pair from map to
extends V> t)) hashtable.

boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the hashtable.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified
newValue) key.

void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.

String toString() It returns a string representation of the Hashtable object.

Collection values() It returns a collection view of the values contained in the


map.

boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.

boolean containsValue(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.

boolean containsKey(Object key) This method return true if some key equal to the key
exists within the hash table, else return false.

boolean isEmpty() This method returns true if the hash table is empty; returns
false if it contains at least one key.
int size() This method returns the number of entries in the hash
table.

Java Hashtable Example


1. import java.util.*;
2. class Hashtable1{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
8. hm.put(101,"Vijay");
9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Test it Now

Output:

103 Rahul
102 Ravi
101 Vijay
100 Amit

Java Hashtable Example: remove()


1. import java.util.*;
2. public class Hashtable2 {
3. public static void main(String args[]) {
4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. System.out.println("Before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("After remove: "+ map);
13. }
14. }

Output:

Before remove: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}


After remove: {103=Rahul, 101=Vijay, 100=Amit}

StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, String creates StringTokenizer with specified string and


delim) delimeter.

StringTokenizer(String str, String creates StringTokenizer with specified string, delimeter


delim, boolean returnValue) and returnValue. If return value is true, delimiter
characters are considered to be tokens. If it is false,
delimiter characters serve to separate tokens.
Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:

Public method Description

boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the StringTokenizer


object.

String nextToken(String delim) returns the next token based on the delimeter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type is Object.

int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class


Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.

1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:my
name
is
khan

Example of nextToken(String delim) method of StringTokenizer


class
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split() method of String class
or regex (Regular Expression).

java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods
to deal with date and time in java.

The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It


is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

After Calendar class, most of the constructors and methods of java.util.Date class has been
deprecated. Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors

No. Constructor Description

1) Date() Creates a date object representing current date and time.

2) Date(long milliseconds) Creates a date object for the given milliseconds since January
1, 1970, 00:00:00 GMT.

java.util.Date Methods
No. Method Description

1) boolean after(Date date) tests if current date is after the given date.

2) boolean before(Date date) tests if current date is before the given date.

3) Object clone() returns the clone object of current date.

4) int compareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for equality.

6) static Date from(Instant returns an instance of Date object from Instant date.
instant)

7) long getTime() returns the time represented by this date object.

8) int hashCode() returns the hash code value for this date object.

9) void setTime(long time) changes the current date and time to given time.

10) Instant toInstant() converts current date into Instant object.

11) String toString() converts this date into Instant object.

java.util.Date Example
Let's see the example to print date in java using java.util.Date class.

1st way:

1. java.util.Date date=new java.util.Date();


2. System.out.println(date);

Output:

Wed Mar 27 08:22:02 IST 2015

2nd way:

1. long millis=System.currentTimeMillis();
2. java.util.Date date=new java.util.Date(millis);
3. System.out.println(date);

Java BitSet Class


The Java BitSet class implements a vector of bits. The BitSet grows automatically as more bits are n
comes under java.util package. The BitSet class extends the Object class and provides the

implementation of Serializable and Cloneable interfaces.

Each component of bit set contains at least one Boolean value. The contents of one BitSet may be

changed by other BitSet using logical AND, logical OR and logical exclusive OR operations.

The index of bits of BitSet class is represented by positive integers.

Each element of bits contains either true or false value. Initially, all bits of a set have the false

value. A BitSet is not safe for multithreaded use without using external synchronization.

Note: Passing a null parameter to any of the methods of BitSet class will throw a NullPointerException.

Java BitSet Methods

Sl Modifier & Method Description


No Type

1 void and(BitSet set) This method is used to perform a logical AND


bit set with the specified argument.

2 void andNot(BitSet set) This method is used to clear the entire bit
corresponding bit is set in the specified BitSet.
3 int cardinality() This method returns the number of b ts set to

4 void clear() This method set false to all bits in this BitSet.

5 void clear(int bitIndex) This method set bit to false of a specified in e

6 void clear(int fromIndex, This method set bits to false from specified
int toIndex)
fromIndex (inclusive) to toIn ex (exclusive).

7 Object clone() This method makes the clo e of this BitSet


equal to it.

8 boolean equals(Object obj) This method is used to compare the current

object with the specified object.

9 void flip(int bitIndex) This method sets the bit


to its complement

at the specified index.

10 void flip(int fromIndex, This method set each bit value to its
int toIndex)
complement from specified fromIndex (i
(exclusive).

11 boolean get(int bitIndex) This method returns the bit value

of the specified index.

12 BitSet get(int fromIn ex, This method returns a new BitSet of bits
int toIndex)
from specified fromIndex (inclusive) to toInde
13 int hashCode() This method returns the hash co
e

value of this BitSet.

14 boolean intersects(BitSet This method returns true if the specified


set)
BitSet set value is also true in this BitSet set v

15 boolea isEmpty() This method returns true


f the current

BitSet does not contain any bit which is

set to true.

16 int length() This method returns the "logical size" of

this BitSet.

17 int nextClearBit(int This method returns the index of first bit


fromIndex)
which set to false that occurs on or

after the specified index.

18 int nextSetBit(int This method returns the index of


fromIndex)
first bit which is set to true that occurs

on or after the specified index.

19 void or(BitSet set) This method is used to perform a logical OR

opertion of this target bit set with the

specified argument.
20 int previousClearBit(int This method returns the index of the
fromIndex)
nearest bit which is set to false which

occurs on or before the specified index.

21 int previousSetBit(int This method returns the index of the


fromIndex)
nearest bit which is set to true which

occurs on or before the specified index.

22 void set(int bitIndex) This method sets true to bit value at the

specified index.

23 void set(int bitIndex, This method sets a bit of specified


boolean value)
bitIndex to the specified boolean value.

24 void set(int fromIndex, This method sets the bits from specified
int toIndex)
fromIndex (inclusive) to toIndex (exclusive) to

25 void set(int fromIndex, This method sets the bits from specified
int toIndex, b olean
fromIndex (inclusive) to toIndex
value)
(exclusive) to specified boolean value.

26 int size() This method returns the number

of bit space actually in use by this BitSet

to represent bit values.

27 IntStream stream() This method returns a stream of indices for


which this BitSet contains a bit.

28 byte[] toByteArray() This method returns a byte array which

contains all the bits of this bit set.

29 long[] toLongArray() This method returns a long array which

contains all the bits of this bit set.

30 String toString() This method returns a string representatio of

31 static BitSet valueOf(byte[] This method returns a new bit set of the
bytes)
given byte array.

32 static BitSet valueOf(long[] This method returns a new bit set


longs)
of the given long array.

33 static BitSet valueOf(ByteBuffer This method returns a new bit set from
bb)
the given byte buffer.

34 static BitSet valueOf(LongBuffer This method returns a new bit set from
lb)
the given long buffer.

Java Calendar Class


Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits
Object class and implements the Comparable interface.
List of Calendar Methods

No Method Description

1. public void add(int field, int Adds the specified (signed) amount of time
amount)
to the given calendar field.

2. public boolean after (Object when) The method Returns true if the time represented

by this Calendar is after the time represented by

when Object.

3. public boolean before(Object The method Returns true if the time represented
when)
by this Calendar is before the time represented by

when Object.

4. public final void clear(int field) Set the given calendar field value and the time

value of this Calendar undefined.

5. public Object clone() Clone method provides the copy of the current

object.

6. public int compareTo(Calendar The compareTo() method of Calendar class


anotherCalendar)
compares the time values (millisecond offsets)

between two calendar object.

7. protected void complete() It fills any unset fields in the calendar fields.
8. protected abstract void It converts the current millisecond time value
computeFields()
time to calendar field values in fields[].

9. protected abstract void It converts the current calendar field values in


computeTime()
fields[] to the millisecond time value time.

10. public boolean equals(Object The equals() method compares two objects for
object)
equality and Returns true if they are equal.

11. public int get(int field) In get() method fields of the calendar are passed

as the parameter, and this method Returns the

value of fields passed as the parameter.

12. public int getActualMaximum(int Returns the Maximum possible value of the calendar f
field) parameter to getActualMaximum() method.

13. public int getActualMinimum(int Returns the Minimum possible value of the
field)
calendar field passed as parameter to

getActualMinimum() methot.

14. public static Set<String> Returns a set which contains string set of
getAvailableCalendarTypes()
all available calendar type supported by Java

Runtime Environment.

15. public static Locale[] Returns an array of all locales available in java
getAvailableLocales()
runtime environment.
16. public String getCalendarType() Returns in string all available calendar type

supported by Java Runtime Environment.

17. public String getDisplayName(int Returns the String representation of the calendar
field, int style, Locale locale)
field value passed as the parameter in a given

style and local.

18. public Map<String,Integer> Returns Map representation of the calendar field


getDisplayNames(int field, int
value passed as the parameter in a given style and
style, Locale locale)

local.

19. public int getFirstDayOfWeek() Returns the first day of the week in integer form.

20. public abstract int This method returns the highest minimum value of
getGreatestMinimum(int field)
Calendar field passed as the parameter.

21. public static Calendar This method is used with calendar object to get the
getInstance()
instance of calendar according to current time zone

set by java runtime environment

22. public abstract int Returns smallest value from all maximum value for
getLeastMaximum(int field)
the field specified as the parameter to the method.

23. public abstract int getMaximum(int This method is used with calendar object to get the
field)
maximum value of the specified calendar field as the pa

24. public int Returns required minimum days in integer form.


getMinimalDaysInFirstWeek()

25. public abstract int getMinimum(int This method is used with calendar object to get the
field) specified calendar field as the parameter.

26. public final Date getTime() This method gets the time value of calendar object

and Returns date.

27. public long getTimeInMillis() Returns the current time in millisecond. This method
type.

28. public TimeZone getTimeZone() This method gets the TimeZone of calendar

object and Returns a TimeZone object.

29. public int getWeeksInWeekYear() Return total weeks in week year. Weeks in

week year is returned in integer form.

30. public int getWeekYear() This method gets the week year represented by

current Calendar.

31. public int hashCode() All other classes in Java overload hasCode() method.

This method Returns the hash code for calendar

object.

32. protected final int internalGet(int This method returns the value of the calendar
field)
field passed as the parameter.

33. Public boolean isLenient() Return Boolean value. True if the interpretation
mode of this calendar is lenient; false otherwise.

34. public final boolean isSet(int field) This method checks if specified field as the

Parameter has been set or not. If not set then

it returns false otherwise true.

35. public boolean Checks if this calendar supports week date.


isWeekDateSupported()
The default value is false.

36. public abstract void roll(int field, This method increase or decrease the specified
boolean up)
calendar field by one unit without affecting the

other field

37. public void set(int field, int value) Sets the specified calendar field by the specified

value.

38. public void setFirstDayOfWeek(int Sets the first day of the week. The value which is to
value)
be set as the first day of the week is passed as

parameter.

39. public void Sets the minimal days required in the first week.
setMinimalDaysInFirstWeek(int
The value which is to be set as minimal days in
value)

first week is passed as parameter.

40. public final void setTime(Date Sets the Time of current calendar object.
date)
A Date object id passed as the parameter.
41. public void setTimeInMillis(long Sets the current time in millisecond.
millis)

42. public void setTimeZone(TimeZone Sets the TimeZone with passed TimeZone
value)
value (object) as the parameter.

43. public void setWeekDate(int Sets the current date with specified integer value
weekYear, int weekOfYear, int
as the parameter. These values are weekYear,
dayOfWeek)
dayOfWeek.

44. public final Instant toInstant() The toInstant() method convert the current object

to an instant.

45. public String toString() Returns string representation of the current object.

Java Vector Class


Java Vector class comes under the java.util package. The vector class implements a growable
array of objects. Like an array, it contains the component that can be accessed using an integer
index.

Vector is very useful if we don't know the size of an array in advance or we need one that can
change the size over the lifetime of a program.

Vector implements a dynamic array that means it can grow or shrink as required. It is similar to
the ArrayList, but with two differences-

o Vector is synchronized.
o The vector contains many legacy methods that are not the part of a collections framework

Vector Declaration:
1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
Java Vector Class Constructors
Vector class supports four types of constructors. These are:

SN Constructor Description

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial


capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, It constructs an empty vector with the specified initial


int capacityIncrement) capacity and capacity increment.

4) Vector( Collection<? It constructs a vector that contains the elements of a


extends E> c) collection c.

Java Vector Class Methods

The following are the list of vector class methods:

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection


to the end of this Vector.

3) addElement() It is used to append the specified component to the end of this


vector. It increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the
specified collection.

10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

13) equals() It is used to compare the specified object with the vector for
equality.

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the
Iterable until all elements have been processed or the action
throws an exception.

16) get() It is used to get an element at the specified position in the vector.

17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.

19) insertElementAt() It is used to insert the specified object as a component in the given
vector at the specified index.

20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper
sequence.

22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the
specified element in the vector. It returns -1 if the vector does
not contain the element.

24) listIterator() It is used to get a list iterator over the elements in the list in proper
sequence.
25) remove() It is used to remove the specified element from the vector. If the
vector does not contain the element, it is unchanged.

26) set() It is used to replace the element at the specified position in the
vector with the specified element.

27) setElementAt() It is used to set the component at the specified index of the vector
to the specified object.

28) setSize() It is used to set the size of the given vector.

29) size() It is used to get the number of components in the given vector.

30) sort() It is used to sort the list according to the order induced by the
specified Comparator.

31) spliterator() It is used to create a late-binding and fail-fast Spliterator over


the elements in the list.

32) subList() It is used to get a view of the portion of the list between fromIndex,
inclusive, and toIndex, exclusive.

33) toArray() It is used to get an array containing all of the elements in this
vector in correct order.

34) toString() It is used to get a string representation of the vector.

35) trimToSize() It is used to trim the capacity of the vector to the vector's
current size.

Example:
1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now

Output:

Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer

You might also like