Unit IV-OOP Java-Part I
Unit IV-OOP Java-Part I
1. Fixed in Size: Once we create an array with some size there is no chance of increasing or
decreasing the size of that array based on our requirement.
2. Hold Homogeneous Elements: Arrays can hold only homogeneous type of elements.
Note:We can solve this problem by using object type arrays.
Object[]a=newObject(10000);
a[0]=newStudent();-(valid)
a[1]=newCustomer();-- (valid)
3. No Readymade Method Support: Arrays are not implemented based on some standard data
structure. So, it is developer’s responsibility to write the code for every requirement like storing
the elements based on some sorting order, search for an element is there or not in the array etc.
4. To use arrays, it is better to know the size in advance, which is may not possible always.
Note:If we know the size in advance, then it is highly recommended to go for arrays.
Because performance wise arrays are better than collections.
Ex:
al 1 2 …………… 1 Crore
Collections(C): Collections is a utility class presents in java.util package to define several utility
methods like sorting, searching etc. in collection objects.
Ex:To sort an ArrayList Collections.sort(al);al ArrayListObject
Arrays vs Collections:
Arrays Collections
1.Array are fixed in size. 1.Collections are growable in nature.
2.W.r.t memory arrays are not 2.W.r.t memory collections are recommended.
recommended.
3.W.r.t performance arrays are 3.W.r.t performance collections are not
recommended. recommended.
4.Arrays can hold only homogeneous 4.Collections can hold both homogeneous and
elements. heterogeneous elements.
5.Arrays are not implemented based on any 5.Every collection class is implemented based on some
DS. So, readymade method support is not standard DS. So, readymade method support is
available. available.
6.Arrays can hold primitive types and 6.Collections can hold only reference types(objects).
Reference types(objects).
7.There are no predefined classes in Java API 7.There are so many predefined classes are available in
which represents arrays. Java API (java.util package) which represents
collections.
Interfaces of Java Collections FrameWork (JCF)
The Java collections framework provides various interfaces. These interfaces include several methods to
perform different operations on collections.
Collection interface is used to represent a group of individual objects as a single entity. It defines the most
common methods which are applicable for many collection objects.
The Collection interface is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface but provides implementations of its
subinterfaces like List, Set, and Queue.
Collections Framework Vs. Collection Interface
The Collection interface is the root interface of the collections framework. The framework includes other
interfaces as well: Map and Iterator. These interfaces may also have subinterfaces.
As mentioned earlier, the Collection interface includes subinterfaces that are implemented by Java classes.
All the methods of the Collection interface are also present in its subinterfaces.
Here are the subinterfaces of the Collection Interface:
List Interface
The List interface is an ordered collection that allows us to add and remove elements like
an array. List is the child interface of Collection interface. If we want to represent a group of
individual objects as single entity where duplicates are allowed and insertion order must be
preserved, then we go for List.
Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics.
It cannot have duplicate elements. Set is the child interface of Collection interface. If we want
to represent a group of individual objects as single entity where duplicates are not allowed and
insertion order not preserved, then we go for Set.
Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner. Queue
is the child interface of Collection. If we want to represent a group of individual objects prior to processing,
then we should go for Queue
Key Value
entry
101 A
102 B
103 C
104 A
Both keys and values are objects only. Duplicate keys are not allowed but duplicate values are
allowed. Each key value pair is called entry. Hence, Map is considered as a collection of entry
objects.
Java Iterator Interface
In Java, the Iterator interface provides methods that can be used to access elements of collections.
The Java collections framework provides various data structures and algorithms that can be used directly. This
has two main advantages:
• We do not have to write code to implement these data structures and algorithms manually.
• Our code will be much more efficient as the collections framework is highly optimized.
Moreover, the collections framework allows us to use a specific data structure for a particular type of data.
Here are a few examples,
• If we want our data to be unique, then we can use the Set interface provided by the collections framework.
• To store data in key/value pairs, we can use the Map interface.
• The ArrayList class provides the functionality of resizable arrays.
Methods of Collection
The Collection interface includes various methods that can be used to perform different operations on objects.
These methods are available in all its subinterfaces.
removeAll() clear()
1.The removeAll() method removes the elements 1.The clear() method blindly removes all theelements
of a collection by comparing with the elements of from a collection.
other collection.
2.The return type is boolean. 2.The return type is void.
3.To perform removeAll() we require two 3.To perform clear() we require only one collection
Collection objects. object.
4.The removeAll() is slower than clear(). 4.The clear() is faster than removeAll().
5.If we observe the implementation of 5.If we observe the implementation of clear(), the time
removeAll(), the time complexity is O(n2). complexity is O(n).
6. Choose ‘removeAll()’ when you want toremove 6. Choose ‘clear()’ method when you want to remove
only certain elements from the collection by all elements from the collection without any cross
comparing with other collection. checks.
Java List
In Java, the List interface is an ordered collection that allows us to store and access elements sequentially. It
extends the Collection interface.
List(I): List is the child interface of Collection interface. If we want to represent a group of
individual objects as single entity where duplicates are allowed and insertion order must be
preserved, then we go for List.
Methods of List
The List interface includes all the methods of the Collection interface. Its because Collection is a super
interface of List.
Some of the commonly used methods of the Collection interface that's also available in the List interface are:
Methods Description
clear() removes all the elements from the list (more efficient than removeAll())
class Main {
Output
List: [1, 2, 3]
Accessed Element: 3
Removed Element: 2
class Main {
List: [1, 2, 3]
Accessed Element: 3
Position of 3 is 1
Removed Element: 2
1. Java ArrayList
In Java, we need to declare the size of an array before we can use it. Once the size of an array is declared, it's
hard to change it.
To handle this issue, we can use the ArrayList class. It allows us to create resizable arrays.
Unlike arrays, arraylists can automatically adjust their capacity when we add or remove elements from them.
Hence, arraylists are also known as dynamic arrays.
Creating an ArrayList
In the above program, we have used Integer not int. It is because we cannot use primitive types while creating
an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int
The ArrayList class provides various methods to perform different operations on arraylists. We will look at
some commonly used arraylist operations in this tutorial:
• Add elements
• Access elements
• Change elements
• Remove elements
Already add(), get(), set(), and remove() method of the ArrayList class are there
Besides these basic methods, here are some more ArrayList methods that are commonly used.
Methods Descriptions
clone() Creates a new arraylist with the same element, size, and capacity.
Searches the arraylist for the specified element and returns a boolean
contains()
result.
Example:
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
}
}
Output
• To add a single element to the arraylist, we use the add() method of the ArrayList class.
• In the above example, we have used the get() method with parameter 1. Here, the method returns the
element at index 1.
• Here, the set() method changes the element at index 2
• Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.
• We can use the Java for-each loop to loop through each element of the arraylist.
ii) Declaration:
Public classArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneab le,
Serializable
iii) Constructors:
(a) ArrayList al=new ArrayList();
Creates an empty ArrayList with default initial capacity 10. Once
ArrayList reaches its maximum capacity then a new ArrayList will be
created with
newcapacity=(currentcapacity*3/2)+1
& with same reference variable(al).
(b) ArrayList al = new ArrayList(int initial_capacity);
Creates an empty ArrayList with specified initial
capacity.
(c) ArrayList al=new ArrayList(Collection c);
Creates an equivalent ArrayList for the given Collection.
ArrayList vs Vector:
ArrayList Vector
1.Every method present in the ArrayList is 1.Every method present in the Vector is synchronized.
non-synchronized.
2.At a time, multiple threads can operate on 2.At a time, only one thread allowed to operate on single
Single ArrayList object and hence it is not vector object and hence it is thread safe.
thread safe.
3.Relatively performance is high because 3.Relatively performance is low because threads are
threads are not required to wait to operate on required to wait to operate on Vector object.
ArrayList object.
4.Introduced in 1.2 version and it is non legacy 4.Introduced in1.0 version and it is legacy.
LinkedList(C)
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. LinkedList is a class presents in
java.util package.
Properties:
The underlying DS is Doubly LinkedList.
Duplicates are allowed and Insertion order is preserved.
Heterogeneous elements are allowed and null insertion is possible.
If our frequent operation is insertion or deletion in the middle, then LinkedList is
the best choice. Because the internal structure of the LinkedList. LinkedList is the
worst choice if our frequent operation is retrieval operation.
Constructors:
(a) LinkedList ll=new LinkedList(); Creates an empty LinkedList object
(b) LinkedList l2=new LinkedList(Collection c);
Creates an equivalent LinkedList object for the given Collection.
Methods of LinkedList:
ArrayList vs LinkedList:
ArrayList LinkedList
1.ArrayList internally uses resizable array or 1.LinkedList internally uses doubly linked list to store
dynamic array to store the elements. the elements.
2. Manipulation with ArrayList is slow because it 2.Manipulation with LinkedList is faster than ArrayList
internally uses array. If any element is removed because it uses doubly linked list so no bit shifting is
from the array, all the bits are shifted in required in memory.
memory.
3.ArrayList class can act as a list only because it 3.LinkedList class can act as a list and queue both
Implements List only. Because it implements List and Deque interfaces.
4.ArrayList is the best choice if our frequent 4.LinkedList is the best choice if our frequent operation
Operation is retrieval. Is insertion or deletion in the middle.
5. In ArrayList elements are stored in 5.In LinkedList elements are not stored in consecutive
Consecutive memory locations. Memory locations.
}
}
Output: Ajay
Vijay
Ravi
Java Vector
Vector(C): The Vector class is an implementation of the List interface that allows us to create
resizable-arrays similar to the ArrayList class. Vector is a class presents in java.util package
which extends(inherits) from AbstractList class and implements from List interfaces.
Properties:
The underlying DS is resizable array or growable array.
Duplicates are allowed and Insertion order is preserved.
Heterogeneous elements are allowed and null insertion is possible.
Every method present in the vector is synchronized and hence vector object is
thread safe.
Declaration:
Public class Vector<E> extends AbstractList<E> implements List<E>
Constructors:
(a) Vector v = new Vector();
Creates an empty vector object with default initial capacity 10. Once Vector reaches its
max capacity then a new vector will be crated with (double) capacity = current
capacity*2.
(b) Vector v =new Vector(int initial_capacity);
Creates an empty Vector object with specified initial capacity.
(c) Vector v =new Vector(Collection c);
Creates an equivalent vector object for the given Collection. This constructor
meant for inter conversion between collection objects.
Methods of Vector:
To add objects
• add(element) - adds an element to vectors
• add(index, element) - adds an element to the specified position
• addAll(vector) - adds all elements of a vector to another vector
To remove objects
• remove(index) - removes an element from specified position
• removeAll() - removes all the elements
• clear() - removes all elements. It is more efficient than removeAll()
To get objects
• get(index) - returns an element specified by the index
• iterator() - returns an iterator object to sequentially access vector elements
Other Methodss
Methods Descriptions
contains() searches the vector for specified element and returns a boolean result
Example:
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);
// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);
// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output
The Java collections framework has a class named Stack that provides the functionality of the
stack data structure. Stack is a class presents in java.util package which extends from Vector
class. So, it is the child class of Vector and it is a specially designed for last-in-first-out (LIFO)
order.
The Stack class extends the Vector class.
Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to the top
of the stack and removed from the top of the stack.
Declaration: Public class Stack<E> extends Vector<E>
Creating a Stack
In order to create a stack, we must import the java.util.Stack package first. Once we import the package, here
is how we can create a stack in Java.
class Main {
public static void main(String[] args) {
Stack<String> s= new Stack<>();
Queue(I): Queue is the child interface of Collection. If we want to represent a group of individual
objects prior to processing, then we should go for Queue. For example, before sending SMS
messages all mobile numbers we have to store in some DS. In which order we added mobile
numbers in the same order only messages should be delivered. For this FIFO requirement Queue
is the best choice.
Since the Queue is an interface, we cannot provide the direct implementation of it.
In order to use the functionalities of Queue, we need to use classes that implement it:
• ArrayDeque
• LinkedList
• PriorityQueue
In queues, elements are stored and accessed in First In, First Out manner. That is, elements are added from the
behind and removed from the front.
Usually Queue follows FIFO order but based on our requirement we can implement our own
priority order also (Priority Queue). LinkedList class also implements Queue interface. LinkedList
based implementation of Queue always follows FIFO order.
In Java, we must import java.util.Queue package in order to use Queue.
Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is because Collection is the super
interface of Queue.
Some of the commonly used methods of the Queue interface are:
• add() - Inserts the specified element into the queue. If the task is successful, add() returns true, if not it
throws an exception.
• offer() - Inserts the specified element into the queue. If the task is successful, offer() returns true, if not it
returns false.
• element() - Returns the head of the queue. Throws an exception if the queue is empty.
• peek() - Returns the head of the queue. Returns null if the queue is empty.
• remove() - Returns and removes the head of the queue. Throws an exception if the queue is empty.
• poll() - Returns and removes the head of the queue. Returns null if the queue is empty.
Implementation of the Queue Interface
class Main {
Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]
Priority Queue(C): Priority Queue is a class presents in java.util package which extends(inherits)
from AbstractQueue class. If we want to represent a group of individual objects prior to processing
according to some priority, then we should go for PriorityQueue. The priority can be either default
natural sorting order or customized sorting order defined by Comparator.
i) Properties:
Insertion order is not preserved and it is based on some priority.
Duplicate objects are not allowed.
Implementing the PriorityQueue Class
import java.util.Queue;
import java.util.PriorityQueue;
class Main {
public static void main(String[] args) {
// Creating Queue using the PriorityQueue class
Queue<Integer> numbers = new PriorityQueue<>();
// offer elements to the Queue
numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
System.out.println("Queue: " + numbers);
// Access elements of the Queue
int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);
// Remove elements from the Queue
int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);
System.out.println("Updated Queue: " + numbers);
}
}
Run Code
Output
Queue: [1, 5, 2]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 5]