0% found this document useful (0 votes)
4 views34 pages

Java Collections

The document provides an overview of arrays and collections in Java, detailing their characteristics, syntax, and usage. It explains the differences between arrays and collections, introduces the Java Collections Framework, and describes various interfaces and classes such as List, Set, Queue, and their methods. Additionally, it includes code examples demonstrating the implementation and manipulation of arrays and collections.

Uploaded by

sudheergoluguri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

Java Collections

The document provides an overview of arrays and collections in Java, detailing their characteristics, syntax, and usage. It explains the differences between arrays and collections, introduces the Java Collections Framework, and describes various interfaces and classes such as List, Set, Queue, and their methods. Additionally, it includes code examples demonstrating the implementation and manipulation of arrays and collections.

Uploaded by

sudheergoluguri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Collections in Java

Section - I
Arrays in Java

An array in Java is a group of like-typed variables referred to by a common name.

Following are some important points about Java arrays:

➢ Arrays are objects in Java, we can find their length using the object property length.
➢ The variables in the array are ordered, and each has an index beginning from 0.

➢ An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class depending on the definition of the array.

Declaration:

Datatype varname[] = new Datatype[] //single Dimensional Array

Syntax:
int[] intArray = new int[20];

Syntax:
int[] intArray = new int[]{ 1,2,3,4,5}; // Declaring array literal

1|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
package ArrayPackage;
public class ArrayClass1 {
public static void main(String[] args) {
int arr[]= new int[5];
arr[0]=10;
arr[1]=11;
arr[2]=12;
arr[3]=13;
arr[4]=14;
[Link]("Printing Arraya Values:");
for (int i=0; i<[Link];i++)
{
[Link]("Arrayn Position :" +(i+1)+" is " +arr[i]);
} } }

package ArrayPackage;
public class ArrayClass2 {
public static void main(String[] args) {
String arr[]= new String[5];
arr[0]="Ramadugu";
arr[1]="New York";
arr[2]="Selenium";
arr[3]="Santhosh";
arr[4]="The Rock";
[Link]("Printing Array Values:");
for (int i=0; i<[Link];i++)
{
[Link]("Array at Position : " +(i+1) +"
is " +arr[i]);
}

for (String s : arr)


{
[Link](s);
}
} }

2|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
package ArrayPackage;
public class ArrayClass3 {
public static void main(String[] args) {
Object arr[]= new Object[5];
arr[0]=123;
arr[1]=345;
arr[2]="Selenium";
arr[3]="Manual";
arr[4]="The Rock";
[Link]("Printing Array Values:");
for (int i=0; i<[Link];i++)
{
[Link]("Array at Position : " +(i+1) +"
is " +arr[i]);
}

for (Object s : arr)


{
[Link](s);
}
}
}

Multi-Dimensional Array:

Multidimensional Arrays can be defined in simple words as array of arrays. Data in


multidimensional arrays are stored in tabular form (in row major order)

Syntax:
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];

3|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
package ArrayPackage;
public class ArrayClass4 {
public static void main(String[] args) {
int arr[][]= new int[2][3];
arr[0][0]=123;
arr[1][0]=345;
int arr1[][] = {{1,2}, {2,3}, {4,5}};
[Link]("Printing Array Values:");
for (int i=0; i<[Link];i++)
{ for(int j=0; j<3; j++)
{[Link](arr[i][j] + " ");}
[Link]();
}
for (int i=0; i<[Link];i++) {
for(int j=0; j<2; j++) {
[Link](arr1[i][j] + " "); }
[Link]();}} }

Sr. Key Arrays Collection


No.

Size Arrays are fixed in size i.e once the The collection is dynamic in size
array with the specific size is i.e based on requirement size
1
declared then we can't alter its size could be get altered even after
afterward. its declaration.

Memory Arrays due to fast execution Collections, on the other hand,


Consumption consumes more memory and has consume less memory but also
2
better performance. have low performance as
compared to Arrays.

Data type Arrays can hold the only the same Collection, on the other hand,
type of data in its collection i.e only can hold both homogeneous
3
homogeneous data types elements and heterogeneous elements.
are allowed in case of arrays.

4|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
Section - II
Collections Framework
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 Collection framework?


The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has: Interfaces and its implementations, i.e., classes
Algorithm

Hierarchy of Collection Framework:

5|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
Methods of Collection interface:

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

No. Method Description

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

2 public boolean addAll(Collection<? It is used to insert the specified collection elements in the
extends E> c) invoking collection.

3 public boolean remove(Object element) It is used to delete an element from the collection.

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

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

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

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

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

9 public boolean contains(Object element) It is used to search an element.

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


containsAll(Collection<?> c)

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the
returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its
source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as its source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the
collection.

18 public boolean equals(Object element) It matches two collections.

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

6|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
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 It returns true if the iterator has more elements otherwise it returns
hasNext() 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.

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.

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.

Set Interface
Set Interface in Java is present in [Link] package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and
TreeSet.

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used
to hold the elements which are about to be processed. There are various classes like PriorityQueue,
Deque, and ArrayDeque which implements the Queue interface.

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements
from both the side. Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.

7|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
➢ Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements
also. We can also store the null elements in the list.

List - Java ArrayList:

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there
is no size limit. We can add or remove elements anytime. So, it is much more flexible than the
traditional array.

Java List Methods


Method Description

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

boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements in the specified collection to the
extends E> c) end of a list.

boolean addAll(int index, It is used to append all the elements in the specified collection, starting
Collection<? extends E> c) at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

boolean equals(Object o) It is used to compare the specified object with the elements of a list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this list in
the correct order.

boolean contains(Object o) It returns true if the list contains the specified element

8|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.

E remove(int index) It is used to remove the element present at the specified position in the
list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.

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

List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given range.
toIndex)

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

Example1:

9|Page
Handbook on Test Automation - Selenium By Manohar Rao BRV
public class Collections1 {
public static void main(String[] args) {
List al = new ArrayList();
[Link](10);
[Link]("SriVidya");
[Link](3.14);
[Link](al);
List<String> a2 = new ArrayList<String>();
//or List<String> a2 = new ArrayList<>();
[Link]("Manohar");
[Link]("Rao");
//[Link](14);
[Link](a2);
//using for each loop
for (String s :a2)
{
[Link](s);
}
//for loop
for (int i =0; i<[Link](); i++)
{
[Link]([Link](i));
}
//Iterator
ListIterator<String> itr = [Link]();
//forward firection
[Link]("In Forward Condition");

while([Link]())
{
[Link]([Link]());
}
//backward direction
[Link]("In Backward Condition");
while([Link]())
{
[Link]([Link]());
}
//only with iterator concept
Iterator itr1 = [Link]();

//forward firection
[Link]("In Forward Condition");

while([Link]())
{
[Link]([Link]());
}
//foreach directly with lamda

[Link](a->{
[Link]("Lamda " +a);
});
///foreachremaining needs Iterator interface
Iterator<String> itr2 = [Link]();
[Link](a->{
[Link]("Lamda with Iterator " +a);
});
} }

10 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example2:
package Javacollections;
import [Link];
import [Link];
import [Link];
import [Link];
public class Collections2 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Before add Leapu" +l1);
[Link](2, "Leapu");
[Link]("After add Leapu" +l1);
List<String> l2 = new ArrayList<>();
[Link]("Satyanarayana");
[Link]("Sussela");
[Link]("Manohar");
[Link]("Dimpu");
[Link]("Printing First List");
for(String s : l1)
{
[Link](s);
}
[Link]("Printing Second List");
for(String a : l2)
{
[Link](a);
}
//addingl1 to l2
[Link]("After adding l1 to l2");
[Link](l1);
for(String b : l2)
{
[Link](b);
}
//inserting middle withrespect to index

[Link]("Inserting Middle with respect to


index");
[Link](1,l1);
for(String c : l2)
{
[Link](c);
}
//l2 clear method to clear all values
[Link]();
} }

11 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example3:

package Javacollections;
import [Link];
import [Link];
import [Link];
import [Link];
public class Collections3 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
List<String> l2 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]([Link](l2));
} }

Example4:
package Javacollections;
import [Link];
import [Link];
import [Link];
import [Link];
public class Collections4 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]([Link]());
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]("Sridhar");
//printing the last index postion
[Link]([Link]("Sridhar"));
//first position check
[Link]([Link]("Sridhar"));
//contains check
[Link]([Link]("Leapu"));
} }

12 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example5:

package Javacollections;

import [Link];
import [Link];
public class Collections5 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]("Sridhar");
[Link]("Before Remove");
[Link](l1);
[Link](3);
[Link]("After Remove with index postion");
[Link](l1);
[Link]("Leapu");
[Link]("After Remove with value");
[Link](l1);
} }

Example6:

package Javacollections;
import [Link];
import [Link];
public class Collections6 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]("Sridhar");
[Link]("Before Replace");
[Link](l1);
//set-replace the values
[Link](5, "SriMaanvith");
[Link]("After Replace");
[Link](l1);} }

13 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example7:

package Javacollections;
import [Link];
import [Link];
import [Link];
public class Collections7 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]("Sridhar");
[Link]("manohar");
//sorting values without case senstive
[Link](String.CASE_INSENSITIVE_ORDER);
[Link](l1);
//sorting with case sensitive
[Link]([Link]());
[Link](l1);
} }

Example8:

package Javacollections;
import [Link];
import [Link];
public class Collections8 {
public static void main(String[] args) {
List<String> l1 = new ArrayList<>();
[Link]("Niranjan");
[Link]("Anjani");
[Link]("Sridhar");
[Link]("SriVani");
[Link]("Srividya");
[Link]("Leapu");
[Link]("Sridhar");
[Link]("manohar");
//list with index value
[Link]([Link](2, 4));
} }

14 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example9-Storing Objects in ArrayList:

package JavaCollections1;
import [Link];
import [Link];
class Students{
int rollno;
String name;
String course;
Students(int r, String n, String c){
[Link] =r;
[Link] = n;
[Link] = c;
}
}
public class Objectsstored {
public static void main(String[] args) {
List<Students> sdetails = new ArrayList<>();
Students s1 = new Students(11, "Manohar", "EEE");
Students s2 = new Students(12, "Jhansi", "PID");
Students s3 = new Students(13, "Sagar", "EPS");
[Link](s1);
[Link](s2);
[Link](s3);
for(Students s : sdetails)
{
[Link]([Link] +" " +[Link] +" " +[Link]);
}
}
}

15 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
List - Java LinkedList:

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

Method Description

boolean add(E e) It is used to append the specified element to the end of


a list.

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

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


extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

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


extends E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void addFirst(E e) It is used to insert the given element at the beginning of


a list.

void addLast(E e) It is used to append the given element to the end of a


list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a specified


element.

Iterator<E> It is used to return an iterator over the elements in a


descendingIterator() deque in reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position


in a list.

E getFirst() It is used to return the first element in a list.

16 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
E getLast() It is used to return the last element in a list.

Example1 for LinkedList:

package JavaCollections1;
import [Link];
import [Link];
class Student{
int rollno;
public String toString()
{
return " " +rollno;
}
Student(int r){
[Link] =r;
} }
public class LinkedListclass {
public static void main(String[] args) {
LinkedList<Student> sdetails = new LinkedList<>();
[Link](new Student(111));
[Link](new Student(122));
[Link](new Student(133));
Iterator i = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}

Example2 Linked List:


package JavaCollections1;

import [Link];
import [Link];
import [Link];
import [Link];

17 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
public class LinkedListclass2 {
public static void main(String[] args) {
//List<String> l2 = new ArrayList<>();
List sadd = new LinkedList<>();
//add
[Link](123);
[Link]("Bhainsa");
[Link](507111);
[Link](sadd);
[Link](2, "BCM");
[Link](0, "Hello");
[Link](sadd);
//addfirst and last
LinkedList<Integer> list1 = new LinkedList<Integer>();
[Link](12); [Link](13);
[Link](34);
[Link](list1);
[Link](000000);
[Link](list1);
[Link](1234);
[Link](list1);
//clear
[Link]();
[Link](list1);
[Link](12); [Link](13);
[Link](34); [Link](356);
[Link](3546); [Link](8678446);
[Link](645867);
for(int i:list1)
{ [Link](i); }
[Link]();
//get and size
for(int i =0; i<[Link]();i++)
{
[Link]([Link](i));
}
//get first and last
[Link]([Link]());
[Link]([Link]());
//remove
[Link](2);
[Link](list1);
//removefirst and last
[Link]();[Link]();
[Link](list1);
} }

18 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
ArrayList LinkedList

1) ArrayList internally uses a dynamic array to store LinkedList internally uses a doubly linked
the elements. list to store the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is removed ArrayList because it uses a doubly linked list,
from the array, all the other elements are shifted in so no bit shifting is required in memory.
memory.

3) An ArrayList class can act as a list only because LinkedList class can act as a list and
it implements List only. queue both because it implements List and
Deque interfaces.

4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

5) The memory location for the elements of an The location for the elements of a linked list is
ArrayList is contiguous. not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity in a


default capacity of 10 is assigned to the ArrayList. LinkedList. In LinkedList, an empty list is
created when a LinkedList is initialized.

7) To be precise, an ArrayList is a resizable array. LinkedList implements the doubly linked list of
the list interface.

19 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
List - Java Vector:

Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-
number of elements in it as there is no size limit.

Java Vector Constructors

Vector class supports four types of constructors. These are given below:

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, int It constructs an empty vector with the specified initial
capacityIncrement) capacity and capacity increment.

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


E> c) collection c.

Java Vector Methods:

SN Method Description

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.

20 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
6) 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.

9) copyInto() It is used to copy the components of the vector into the specified array.

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.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if
necessary. It ensures that the vector can hold at least the number of
components specified by the minimum capacity argument.

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.

21 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
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) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.

27) removeAllElements() It is used to remove all elements from the vector and set the size of the
vector to zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the


argument from the vector.

29) removeElementAt() It is used to delete the component at the specified index.

30) removeIf() It is used to remove all of the elements of the collection that satisfy the
given predicate.

31) removeRange() It is used to delete all of the elements from the vector whose index is
between fromIndex, inclusive and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of applying
the operator to that element.

33) retainAll() It is used to retain only that element in the vector which is contained in
the specified collection.

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

35) setElementAt() It is used to set the component at the specified index of the vector to the

22 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
specified object.

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

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

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

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the
elements in the list.

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

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

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

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

23 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Example for Vector:
package JavacollectionsVector;
import [Link];
public class Vectorclass {
public static void main(String[] args) {
Vector v = new Vector();
[Link]([Link]());
[Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse"); [Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse"); [Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse"); [Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse");
[Link]([Link]());
//assigning capacity
Vector v1 = new Vector(4);
[Link]([Link]());
[Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse");
// capacity double
[Link]("Chandra");
[Link]("Gouse");
[Link]([Link]());
//assigning capacity with added capacity
Vector v2 = new Vector(4,2);
[Link]([Link]());
[Link](123);
[Link]("Mukunda"); [Link]("Chandra");
[Link]("Gouse");
// capacity added
[Link]("Chandra");
[Link]([Link]());
[Link]([Link]());
}
}

24 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of Vector increments 100% means doubles the array
current array size if the number of size if the total number of elements exceeds than its
elements exceeds from its capacity. capacity.

3) ArrayList is not a legacy class. It Vector is a legacy class.


is introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized, i.e., in a


synchronized. multithreading environment, it holds the other threads
in runnable or non-runnable state until current thread
releases the lock of the object.

List - Java Stack:

The stack is a linear data structure that is used to store the collection of objects. It is based on Last-
In-First-Out (LIFO). Java collection framework provides many interfaces and classes to store
the collection of objects. One of them is the Stack class that provides different operations such
as push, pop, search, etc.

The stack data structure has the two most important operations that are push and pop. The push
operation inserts an element into the stack and pop operation removes an element from the top of the
stack.

25 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Methods of the Stack Class:

Method Modifier and Method Description


Type

empty() boolean The method checks the stack is empty or not.

push(E item) E The method pushes (insert) an element onto the top of the stack.

pop() E The method removes an element from the top of the stack and returns
the same element as the value of that function.

peek() E The method looks at the top element of the stack without removing it.

search(Object int The method searches the specified object and returns the position of
o) the object.

package JavaCollectionsStack;
import [Link];
import [Link];
public class Stackclass {
public static void main(String[] args) {
Stack st = new Stack();
//push
[Link](12);
[Link](4);
[Link]("Hai");
[Link](st);
/pop
[Link]();
[Link](st);
//peek - reads top element
[Link]([Link]());
//checking is Stack is empty or not
[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]([Link]());
Stack st1 = new Stack();
//push
[Link](12);
//search
[Link]([Link](12)); } }

26 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
➢ Java Set:
It represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and
TreeSet.

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

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 It is used to return true if this set contains the specified element.
o)

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 It is used to remove the specified element from this set if it is
o) present.

27 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
8) int size() It is used to return the number of elements in the set.

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


the elements in the set.

package JavacollectionsHashSet;
import [Link];
public class HasSetclass1 {
public static void main(String[] args) throws
InterruptedException {
HashSet hs = new HashSet();
[Link]("Printing");
[Link]("Writing");
[Link]("Playing");
[Link]("Fighting");
[Link]("Jogging");
[Link]("Running");
[Link](hs);

HashSet<String> hs1 = new HashSet<String>();

[Link]("Printing");
[Link]("Writing");
[Link]("Playing");
[Link]("Fighting");
[Link]("Jogging");
[Link]("Running");
[Link]("Running");//not printing the duplicate values

for(String s : hs1)
{
[Link](s);
}

28 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Key ArrayList HashSet

Implementation ArrayList is the implementation of the list interface. HashSet on the other hand is the
implementation of a set interface.

Internal ArrayList internally implements array for its HashSet internally uses
implementation implementation. Hashmap for its implementation.

Order of ArrayList maintains the insertion order i.e order of the HashSet is an unordered
elements object in which they are inserted. collection and doesn't maintain
any order.

Duplicates ArrayList allows duplicate values in its collection. On other hand duplicate
elements are not allowed in
Hashset.

Index ArrayList uses index for its performance i.e its index HashSet is completely based on
performance based one can retrieve object by calling get(index) or object also it doesn't provide
remove objects by calling remove(index) get() method.

Set - Java LinkedHashSet:

Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface. It
inherits HashSet class and implements Set interface.

The important points about Java LinkedHashSet class are:


o Java LinkedHashSet class contains unique elements only like HashSet.
o Java LinkedHashSet class provides all optional set operation and permits null elements.
o Java LinkedHashSet class is non synchronized.
o Java LinkedHashSet class maintains insertion order.

package JavaCollectionsLinkedHashSet;
import [Link];
public class LinkedHashSetclass {
public static void main(String[] args) {
LinkedHashSet<String> lhs= new LinkedHashSet<String>();
[Link]("Printing"); [Link]("Writing");
[Link]("Playing"); [Link]("Fighting");
[Link]("Jogging"); [Link]("Running");
[Link]("Running");//not printing the duplicate values
for(String s : lhs)
{
[Link](s);
}
} }

29 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Set - Java TreeSet:

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.

TreeSet Exaample1:
package JavaCollectionTreeSet;

import [Link];
import [Link];

public class TreeSetclass {

public static void main(String[] args) {


TreeSet<String> ts= new TreeSet<String>();
[Link]("Printing");
[Link]("Writing");
[Link]("Playing");
[Link]("Fighting");
[Link]("Jogging");
[Link]("Running");
[Link]("Running");//not printing the duplicate
values
//ordering as Ascending
for(String s : ts)
{
[Link](s);
}
//ordering as Descending
Iterator i=[Link]();
while([Link]())
{
[Link]([Link]());
}

30 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Method Description

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


this set if it is not already present.

Iterator descendingIterator() It is used iterate the elements in


descending order.

SortedSet headSet(E toElement) It returns the group of elements that are


less than the specified element.

NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are
less than or equal to(if, inclusive is true)
the specified element.

NavigableSet subSet(E fromElement, boolean fromInclusive, E It returns a set of elements that lie
toElement, boolean toInclusive) between the given range.

SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie


between the given range which includes
fromElement and excludes toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are


greater than or equal to the specified
element.

package JavaCollectionTreeSet;
import [Link];
public class TreeSetclass2 {
public static void main(String[] args) {
TreeSet ts= new TreeSet();
[Link](7); [Link](4575);
[Link](5757); [Link](6436);
[Link](7372); [Link](647);
[Link](7347);
//print less than 5000
TreeSet tl = (TreeSet) [Link](5000);
[Link](tl);
//print more than 5000
TreeSet th = (TreeSet) [Link](5000);
[Link](th);
//print between 5000 and 7000
TreeSet tb = (TreeSet) [Link](5000, 7000);
[Link](tb);
//with respect to Stringvalues
TreeSet tstring= new TreeSet();
[Link]("Printing"); [Link]("Writing");
[Link]("Playing"); [Link]("Fighting");
[Link]("Jogging"); [Link]("Running");
[Link]("Running");
[Link](tstring);
} }

31 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
Java Map Interface
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.

Three classes: HashMap, LinkedHashMap, and TreeMap.

Map – HashMap:

Java HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the element of
the corresponding key. It is easy to perform operations using the key index like updation,
deletion, etc. Java HashMap maintains no order. The initial default capacity of Java HashMap
class is 16 with a load factor of 0.75.

Method Description

void clear() It is used to remove all of the mappings from this


map.

boolean isEmpty() It is used to return true if this map contains no


key-value mappings.

V put(Object key, Object value) It is used to insert an entry in the map.

V remove(Object key) It is used to delete an entry for the specified key.

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

V get(Object key) This method returns the object that contains the
value associated with the key.

boolean isEmpty() This method returns true if the map is empty;


returns false if it contains at least one key.

Collection<V> values() It returns a collection view of the values contained


in the map.

int size() This method returns the number of entries in the


map.

32 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
package Mappackage;
import [Link];
public class Hasmapclass {
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap();
[Link]("Ramesh", 10);
[Link]("Sathish", 12);
[Link]("Honey", 15);
[Link]("Haresh", 15);
[Link]("Bhanu", 15);
[Link]("Sirisha", 15);
[Link]("Sandip", 15);
[Link]("Honey", 20);//it will be overrided
[Link]("Victor", 30);
[Link](hm);
HashMap hm1 = new HashMap();
[Link]("H","Honey");
[Link]("MB", "Mahesh Babu");
[Link]("S", "Sri Devi");
[Link]("H", "Hari");//override
[Link]("T", "Tippu");
[Link]("M", "Reddy");
[Link]("S", "Suresh");//override
[Link](hm1);
[Link]("M");
[Link](hm1);
[Link]([Link]("T"));
[Link]();
} }

Map – LinkedHashMap:

Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map interface.
Java LinkedHashMap maintains insertion order and Java LinkedHashMap may have one null key
and multiple null values.
package Mappackage;
import [Link];
import [Link];
public class LinkedHasmapclass {
public static void main(String[] args) {
HashMap lhm1 = new HashMap();
[Link]("H","Honey"); [Link]("MB", "Mahesh Babu");
[Link]("S", "Sri Devi");
[Link]("H", "Hari");//override
[Link]("T", "Tippu"); [Link]("M", "Reddy");

33 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV
[Link]("S", "Suresh");//override

[Link](lhm1);
[Link]("M");
[Link](lhm1);
[Link]([Link]("T"));
[Link]();
[Link](lhm1);
} }

Map – TreeMap:
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of
storing key-value pairs in sorted order. Java TreeMap maintains ascending order.

package Mappackage;
import [Link];
import [Link];
import [Link];
public class TreeMapclass {
public static void main(String[] args) {
TreeMap tm = new TreeMap();
[Link]("H","Honey");
[Link]("MB", "Mahesh Babu");
[Link]("S", "Sri Devi");
[Link]("H", "Hari");//override
[Link]("T", "Tippu");
[Link]("M", "Reddy");
[Link]("S", "Suresh");//override
[Link](tm);
[Link]("M");
[Link](tm);
[Link]([Link]("T"));

[Link](tm);
//descending order
[Link]("descendingMap:
"+[Link]());
[Link]();

[Link](tm);
}

34 | P a g e
Handbook on Test Automation - Selenium By Manohar Rao BRV

You might also like