0% found this document useful (0 votes)
5 views88 pages

Unit2

This document provides an overview of Java Collections and Utility Classes, focusing on generics, collection hierarchy, and various collection types such as ArrayList, LinkedList, and Vector. It highlights the advantages of using generics for type safety, compile-time checking, and ease of maintenance, as well as the benefits of the Java Collections Framework for code reusability and quality. Additionally, it explains the use of iterators for traversing collections and includes examples of generic methods and classes in Java.

Uploaded by

kibat40952
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)
5 views88 pages

Unit2

This document provides an overview of Java Collections and Utility Classes, focusing on generics, collection hierarchy, and various collection types such as ArrayList, LinkedList, and Vector. It highlights the advantages of using generics for type safety, compile-time checking, and ease of maintenance, as well as the benefits of the Java Collections Framework for code reusability and quality. Additionally, it explains the use of iterators for traversing collections and includes examples of generic methods and classes in Java.

Uploaded by

kibat40952
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
You are on page 1/ 88

Unit 2:

Java Collections and Utility Classes

Introductions to generics: generic types and


methods

Collection Basics- A Collection Hierarchy, Using


ArrayList and Vector, LinkedList, making use of
Iterator to access collection elements
Generics in Java
• The Java Generics programming is introduced to deal
with type-safe objects. It makes the code stable by
detecting the bugs at compile time.

• Before introducing generics, we used to store any type of


objects in the collection, i.e., non-generic. Now generics
force the Java programmer to store a specific type of
objects.

Advantage of Java Generics


• There are mainly three advantages of generics. They are
as follows:

1) Type-safety: We can hold only a single type of objects in


generics. It does not allow to store other objects
Without Generics, we can store any type of
objects.

List list = new ArrayList();


list.add(10);
list.add("10");
With Generics, it is required to specify the type of
object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
2) Type casting is not required: There is no need to
typecast the object.

Before Generics, we need to type cast.

List list = new ArrayList();


list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0)
3) Compile-Time Checking: It is checked at compile time
so problem will not occur at runtime. The good
programming strategy says it is far better to handle the
problem at compile time than runtime.

List<String> list = new ArrayList<String>();


list.add("hello");
list.add(32);//Compile Time Error
public class GenericMethodtest
{
public static <E> void printarray(E[] inputarray)
{

for (E element :inputarray)


{
System.out.printf("%s",element);
}
System.out.println();
}

public static void main(String args[])


{
Integer[] intarray={1,2,3,4,5};
Character[] chararray={'a','b','c','d'};
System.out.println("array in integer");
printarray(intarray);
System.out.println("array in character");
printarray(chararray);
}
}
public class GenericMethod1{
public static void main(String[] args) {
Integer[] intArray = { 1, 2, 3, 4, 5 };
String[] stringArray = { "Hello", "World", "!" };
System.out.print("Integer Array: ");
printArray(intArray);
System.out.print("String Array: ");
printArray(stringArray);
}
public static <T> void printArray(T[] arr) {
for (T element : arr) {
System.out.print(element + " ");
}
System.out.println();
}
}
public class methodp1 {
// Generic method to compare two objects
public static <T extends Comparable<T>> T findMax(T x, T y) {
return x.compareTo(y) > 0 ? x : y;
}

public static void main(String[] args) {


// Using generic method to find maximum of two integers
Integer maxInt = findMax(5, 10);
System.out.println("Maximum of 5 and 10 is: " + maxInt);

// Using generic method to find maximum of two doubles


Double maxDouble = findMax(3.5, 7.8);
System.out.println("Maximum of 3.5 and 7.8 is: " + maxDouble);

// Using generic method to find maximum of two strings


String maxString = findMax("apple", "banana");
System.out.println("Maximum of 'apple' and 'banana' is: " + maxString);
}
}
public class GenericClass<T1,T2>
{
public void disply (T1 var1, T2 var2)
{
System.out.println("Name: "+var1+", ID:"+var2);
}
public static void main(String[] args)
{
GenericClass<String,Integer> obj1=new
GenericClass<String,Integer>();

obj1.disply("abc",101);
}
}
public class AreaG<T> {

// T is the Datatype like String,


// Integer of which Parameter type,
// the class Area is of
private T t;

public void add(T t)


{
// this.t specify the t variable inside
// the Area Class whereas the right hand
// side t simply specify the value as the
// parameter of the function add()
this.t = t;
}

public T get() { return t; }


public static void main(String[] args)
{
// Object of generic class Area with parameter Type
// as Integer
AreaG<Integer> rectangle = new AreaG<Integer>();
// Object of generic class Area with parameter Type
// as Double
AreaG<Double> circle = new AreaG<Double>();
rectangle.add(10);
circle.add(2.5);
System.out.println(rectangle.get());
System.out.println(circle.get());
}
}
Collection Basics-

Collections in Java

• 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).
Collection Hierarchy,

• Let's see the hierarchy of Collection framework. The


java.util package contains all the classes and
interfaces for the Collection framework.

• The Java Collections Framework is structured around


key interfaces-Collection, List, Set, Queue, and Map.
Each tailored for specific data management tasks.

• Implementations like ArrayList, HashSet, and


HashMap offer practical solutions for working with
these collections, giving Java developers a versatile
set of tools for efficient data handling.
Class: A class is a blueprint from which individual
objects are created. It encapsulates data for objects
through fields (attributes) and defines behavior via
methods. Classes support inheritance, allowing one
class to inherit the properties and methods of another,
facilitating code reuse and polymorphism.

Interface: An interface is a reference type in Java that


can contain constants and abstract methods (methods
without a body). Interfaces specify what a class must
do but not how it does it, enforcing a set of methods
that the class must implement. Interfaces are used to
achieve abstraction and multiple inheritance in Java.
Advantages of the Java Collection Framework

The Java Collections Framework offers significant advantages


that enhance development practices, code quality, and
application performance:

1.Reusability: The framework provides a comprehensive set of


common classes and utility methods applicable across various
types of collections. This feature promotes code reusability,
sparing developers the need to write duplicate code for
common operations.

2.Quality: Leveraging the Java Collections Framework elevates


the quality of programs. The components within the framework
have been extensively tested and are widely used by a vast
community of developers, ensuring reliability and stability in
your applications.
3.Speed: Developers often report an increase in development
speed when using the Collections Framework. It allows them to
concentrate on the core business logic of their applications rather
than on implementing generic collection functionalities, thus
speeding up the development process.

4.Maintenance: The open-source nature of the Java Collections


Framework, coupled with readily available API documentation,
facilitates easier code maintenance. Code written using the
framework can be easily understood and taken over by other
developers, ensuring continuity and ease of maintenance.
5.Reduces Effort to Design New APIs: An additional
benefit is the reduced necessity for API designers and
implementers to create new collection mechanisms for
each new API. They can instead rely on the standard
collection interfaces provided by the framework,
streamlining the API development process and ensuring
consistency across Java applications.
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:

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


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
ArrayList

• The ArrayList class implements the List


interface. It uses a dynamic array to store the
duplicate element of different data types.

• The ArrayList class maintains the insertion


order and is non-synchronized.

• The elements stored in the ArrayList class can


be randomly accessed. Consider the following
example.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new
ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ravi
Vijay
Ravi
Ajay
Iterating ArrayList using Iterator

• Iterating through an ArrayList using an Iterator in Java is a


common operation that allows you to traverse the list's
elements sequentially.

• Iterators provide a safe and efficient way to access elements


in a collection, especially when you want to perform
operations like removing elements during iteration.

• Iterating through an ArrayList using a for-each loop, also


known as an enhanced for loop, provides a concise and
readable way to access elements in the list sequentially.

• This approach simplifies the code and is especially useful


when you only need to iterate through the elements without
requiring the index or performing complex operations.
• With the introduction of generics in Java the Collections
Framework became generic.

• Generics allow you to specify the type of elements a


collection can hold at compile time, providing type safety
and eliminating the need for explicit type casting.

• Here's an example of creating a generic ArrayList:

• ArrayList<String> list=new ArrayList<String>();//creating new


generic arraylist

• In this generic ArrayList, the type parameterspecifies that the


ArrayList can only contain elements of type String.

• If you try to add an element of any other type, the compiler


will give a compile-time error, ensuring type safety.

• For example, attempting to add an Integer to this ArrayList


would result in a compile-time error.
Java Iterator

• An Iterator is an object that can be used to loop


through collections, like ArrayList and HashSet.
It is called an "iterator" because "iterating" is
the technical term for looping.

• To use an Iterator, you must import it from the


java.util package.
Advantages of Java Iterator

• The user can apply these iterators to any of the


classes of the Collection framework.

• In Java Iterator, we can use both of the read and


remove operations.

• The Java Iterator is considered the Universal Cursor


for the Collection API.

• The method names in the Java Iterator are very easy


and are very simple to use.
Disadvantages of Java Iterator

• The Java Iterator only preserves the iteration in the


forward direction. In simple words, the Java Iterator
is a uni-directional Iterator.

• Java Iterator does not support traversing elements in


the parallel pattern which implies that Java Iterator
supports only Sequential iteration.

• Java Iterator does not support more reliable


execution to traverse the bulk volume of data.
How to use Java Iterator?

• When a user needs to use the Java Iterator, then it's


compulsory for them to make an instance of the
Iterator interface from the collection of objects
they desire to traverse over.

• After that, the received Iterator maintains the trail


of the components in the underlying collection to
make sure that the user will traverse over each of
the elements of the collection of objects.
Java Iterator Methods

hasNext()

boolean hasNext(): The method does not accept any parameter. It returns true
if there are more elements left in the iteration. If there are no more elements
left, then it will return false.
If there are no more elements left in the iteration, then there is no need to
call the next() method. In simple words, we can say that the method is used to
determine whether the next() method is to be called or not.

next()

E next(): It is similar to hasNext() method. It also does not accept any


parameter. It returns E, i.e., the next element in the traversal. If the iteration
or collection of objects has no more elements left to iterate, then it throws
the NoSuchElementException.
// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

// Print the first item


System.out.println(it.next());
}
}
// Import the ArrayList class and the Iterator class
import java.util.ArrayList;
import java.util.Iterator;

public class MainArr {


public static void main(String[] args) {

// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");

// Get the iterator


Iterator<String> it = cars.iterator();

System.out.println(cars);

}
}
How to Sort ArrayList?

• The java.util package provides a utility class


Collections, which has the static method
sort().

• Using the Collections.sort() method, we can


easily sort the ArrayList.
public class SortingPracticeMain {
public static void main(String[] args) {

ArrayList<String> arrayList = new ArrayList<>();

arrayList.add("Sourav Ganguly");
arrayList.add("Sachin Tendulkar");
arrayList.add("Rahul Dravid");
arrayList.add("Zaheer Khan");
arrayList.add("Yuvraj Singh");
arrayList.add("Harbhajan Singh");
arrayList.add("Javagal Srinath");
arrayList.add("Ashish Nehra");
arrayList.add("Virender Sehwag");
arrayList.add("Ajit Agarkar");
arrayList.add("Mohammad Kaif");

System.out.println("Unsorted list: " + arrayList);

Collections.sort(arrayList);

System.out.println("Sorted list: " + arrayList);


}
}
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.
How Does LinkedList work Internally?

• Since a LinkedList acts as a dynamic array and we do not


have to specify the size while creating it, the size of the list
automatically increases when we dynamically add and
remove items.

• And also, the elements are not stored in a continuous


fashion. Therefore, there is no need to increase the size.
Internally, the LinkedList is implemented using the doubly
linked list data structure.

• The main difference between a normal linked list and a


doubly LinkedList is that a doubly linked list contains an
extra pointer, typically called the previous pointer, together
with the next pointer and data which are there in the singly
linked list
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new
LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ravi
Vijay
Ravi
Ajay
Vector

• Vector uses a dynamic array to store the


data elements.

• It is similar to ArrayList.

• However, it is synchronized and contains


many methods that are not the part of
Collection framework.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ayush
Amit
Ashish
Garima
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.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ayush
Garvit
Amit
Ashish
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
stack.pop();
System.out.println("After POP");
for (String element : stack) {
System.out.println(element);
}
}
}
Set Interface

• Set Interface in Java is present in java.util


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.
Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet
HashSet class implements Set Interface. It represents the collection that uses a
hash table for storage. Hashing is used to store the elements in the HashSet. It
contains unique items.

import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also
contains unique elements. It maintains the insertion order and permits null
elements.

import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ravi
Vijay
Ajay
SortedSet Interface

SortedSet is the alternate of Set interface that provides


a total ordering on its elements. The elements of the
SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods
that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

SortedSet<data-type> set = new TreeSet();


TreeSet

• Java TreeSet class implements the Set interface that


uses a tree for storage.

• Like HashSet, TreeSet also contains unique elements.

• However, the access and retrieval time of TreeSet is


quite fast. The elements in TreeSet stored in ascending
order.
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:

Ajay
Ravi
Vijay
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
// Adding elements to the ArrayList
arrayList.add("Element 1");
arrayList.add("Element 2");
arrayList.add("Element 3");
// Accessing elements using index
System.out.println("Element at index 0: " +
arrayList.get(0));
System.out.println("Element at index 1: " +
arrayList.get(1));
System.out.println("Element at index 2: " +
arrayList.get(2));
// Iterating through the ArrayList
System.out.println("ArrayList Elements:");
for (String element : arrayList) {
System.out.println(element);
}
// Removing an element
arrayList.remove("Element 2");
// Size of the ArrayList after removal
System.out.println("Size of ArrayList after removal: " +
arrayList.size());
}
}
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
// Creating a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to the LinkedList
linkedList.add("Element A");
linkedList.add("Element B");
linkedList.add("Element C");
// Accessing elements using index
System.out.println("Element at index 0: " +
linkedList.get(0));
System.out.println("Element at index 1: " +
linkedList.get(1));
System.out.println("Element at index 2: " +
linkedList.get(2));
// Iterating through the LinkedList
System.out.println("LinkedList Elements:");
for (String element : linkedList) {
System.out.println(element);
}
// Removing an element
linkedList.remove("Element B");
// Size of the LinkedList after removal
System.out.println("Size of LinkedList after removal: " +
linkedList.size());
}
}
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();
// Adding elements to the Vector
vector.add("Item X");
vector.add("Item Y");
vector.add("Item Z");
// Accessing elements using index
System.out.println("Element at index 0: " +
vector.get(0));
System.out.println("Element at index 1: " +
vector.get(1));
System.out.println("Element at index 2: " +
vector.get(2));
// Iterating through the Vector
System.out.println("Vector Elements:");
for (String element : vector) {
System.out.println(element);
}
// Removing an element
vector.remove("Item Y");
// Size of the Vector after removal
System.out.println("Size of Vector after removal: " +
vector.size());
}
}

You might also like