VIPS OOPS Unit 2 Collection API interface
VIPS OOPS Unit 2 Collection API interface
ArrayList increases its size by 50% of the array size. Vector increases its size by doubling the array size.
ArrayList is not ,thread-safe, as it is not synchronized. Vector list is ,thread-safe, as it,s every method is
synchronized.
What is the difference between ArrayList and
LinkedList?
ArrayList LinkedList
ArrayList uses a dynamic array. LinkedList uses a doubly linked list.
ArrayList is not efficient for LinkedList is efficient for manipulation.
manipulation because too much is
required.
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.
ArrayList provides random access. LinkedList does not provide random
access.
ArrayList takes less memory overhead as LinkedList takes more memory overhead,
it stores only object as it stores the object as well as the
address of that object.
What is the difference between Iterator and
ListIterator?
Iterator ListIterator
The Iterator traverses the elements in the forward ListIterator traverses the elements in backward and
direction only. forward directions both.
2)The Iterator can be used in List, Set, and Queue. ListIterator can be used in List only.
3)The Iterator can only perform remove operation while ListIterator can perform add,removeand set operation
traversing the collection. while traversing the collection.
Java Iterator
• 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.
• Getting an Iterator
• The iterator() method can be used to get an Iterator for any collection:
Java Iterator and Advantage
How to use Java Iterator? • Advantages of Java Iterator
• When a user needs to use the Java Iterator, then it's • Iterator in Java became very prevalent due to its
compulsory for them to make an instance of the numerous advantages. The advantages of Java
Iterator interface from the collection of objects they Iterator are given as follows -
desire to traverse over. After that, the received Iterator
maintains the trail of the components in the underlying • The user can apply these iterators to any of the
collection to make sure that the user will traverse over classes of the Collection framework.
each of the elements of the collection of objects.
• In Java Iterator, we can use both of the read and
remove operations.
• If the user modifies the underlying collection while • If a user is working with a for loop, they cannot
traversing over an Iterator leading to that collection, modernize(add/remove) the Collection, whereas, if
then the Iterator will typically acknowledge it and will they use the Java Iterator, they can simply update
throw an exception in the next time when the user will the Collection.
attempt to get the next component from the Iterator.
Disadvantages of Java Iterator
Despite the numerous advantages, the Java Iterator has various
disadvantages also. The disadvantages of the Java Iterator are given
• Java Iterator Methods
below -
• The following figure perfectly
displays the class diagram of the
• The Java Iterator only preserves the iteration in the forward
direction. In simple words, the Java Iterator is a uni-directional
Java Iterator interface. It
Iterator. contains a total of four methods
• The replacement and extension of a new component are not that are:
approved by the Java Iterator.
• In CRUD Operations, the Java Iterator does not hold the various
operations like CREATE and UPDATE.
• hasNext()
• In comparison with the Spliterator, Java Iterator does not support
traversing elements in the parallel pattern which implies that Java
Iterator supports only Sequential iteration.
• next()
• In comparison with the Spliterator, Java Iterator does not support • remove()
more reliable execution to traverse the bulk volume of data.
• forEachRemaining()
Java Iterator Methods
• The forEachRemaining() method • E next(): It is similar to hasNext() method. It
also does not accept any parameter. It returns
was added in the Java 8. Let's E, i.e., the next element in the traversal. If the
discuss each method in detail. iteration or collection of objects has no more
elements left to iterate, then it throws the
NoSuchElementException.
• boolean hasNext(): The method • default void remove(): This method also does
not require any parameters. There is no return
does not accept any parameter. It type of this method. The main function of this
returns true if there are more method is to remove the last element returned
by the iterator traversing through the
elements left in the iteration. If underlying collection.
there are no more elements left,
then it will return false.
Java Iterator Methods
• default void
forEachRemaining(Consumer action):
It is the only method of Java Iterator that
takes a parameter. It accepts action as a
parameter. Action is nothing but that is to
be performed. There is no return type of
the method. This method performs the
particularized operation on all of the left
components of the collection until all the
components are consumed or the action
throws an exception. Exceptions thrown
by action are delivered to the caller. If the
action is null, then it throws a
NullPointerException.
Iterator Example
import java.io.*; System.out.println("CityNames elements : ");
import java.util.*;
public class JavaIteratorExample { while (iterator.hasNext())
public static void main(String[] args)
System.out.print(iterator.next() + " ");
{
System.out.println();
ArrayList<String> cityNames = new ArrayList<String>();
}
cityNames.add("Delhi");
}
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh"); Output:
cityNames.add("Noida");
// Iterator to iterate the cityNames CityNames elements:
Iterator iterator = cityNames.iterator(); Delhi Mumbai Kolkata Chandigarh Noida
Java Vector
• Vector is like the dynamic array which can grow or • It is similar to the ArrayList, but with
shrink its size. Unlike array, we can store n- two differences-
number of elements in it as there is no size limit. It
is a part of Java Collection framework since Java
1.2. It is found in the java.util package and
implements the List interface, so we can use all the
• Vector is synchronized.
methods of List interface here. • Java Vector contains many legacy
methods that are not the part of a
collections framework.
• It is recommended to use the Vector class in the
thread-safe implementation only. If you don't need • Java Vector class Declaration
to use the thread-safe implementation, you should • public class Vector<E>
use the ArrayList, the ArrayList will perform better
in such case. • extends Object<E>
• The Iterators returned by the Vector class are fail- • implements List<E>, Cloneable,
fast. In case of concurrent modification, it fails and Serializable
throws the ConcurrentModificationException.
Java Vector Constructors
• Vector class supports four types of constructors. These are
given below:
Vector Methods
Java Vector Methods
Java Vector Example //Adding elements using addElement() method of
Vector
import java.util.*; vec.addElement("Rat");
public class VectorExample { vec.addElement("Cat");
vec.addElement("Deer");
public static void main(String
args[]) { System.out.println("Elements are: "+vec);
//Create a vector }
Vector<String> vec = new }
Vector<String>(); • Output:
//Adding elements using add() • Compile by: javac VectorExample.java
method of List
vec.add("Tiger"); • Run by: java VectorExample
vec.add("Lion");
vec.add("Dog"); • Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
vec.add("Elephant");
Vector Example Output:
//Display the vector elements Values in vector: [100,
System.out.println("Values in vector: " +in); 200, 300, 200, 400, 500,
import java.util.*; //use remove() method to delete the first occurence of an element 600, 700]
public class VectorExample2 { System.out.println("Remove first occourence of element 200: Remove first occourence
"+in.remove((Integer)200)); of element 200: true
public static void main(String args[]) {
//Display the vector elements afre remove() method Values in vector: [100,
//Create an empty Vector
System.out.println("Values in vector: " +in); 300, 200, 400, 500, 600,
Vector<Integer> in = new Vector<>();
//Remove the element at index 4 700]
//Add elements in the vector System.out.println("Remove element at index 4: " +in.remove(4));
Remove element at index
in.add(100); System.out.println("New Value list in vector: " +in);
4: 500
New Value list in vector:
in.add(200); //Remove an element
[100, 300, 200, 400, 600,
in.add(300); in.removeElementAt(5);
700]
//Checking vector and displays the element
in.add(200); Vector element after
System.out.println("Vector element after removal: " +in);
in.add(400); removal: [100, 300, 200,
//Get the hashcode for this vector
in.add(500);
400, 600]
System.out.println("Hash code of this vector = "+in.hashCode()); Hash code of this vector =
in.add(600); //Get the element at specified index 130123751
in.add(700); System.out.println("Element at index 1 is = "+in.get(1)); Element at index 1 is =
} } 300
What is the difference between Iterator and
Enumeration?
Iterator Enumeration
1) The Iterator can traverse legacy and non- Enumeration can traverse only legacy elements.
legacy elements.
4) The Iterator can perform remove operation The Enumeration can perform only traverse operation
while traversing the collection. on the collection.
What is the difference between List and Set?
8) What is the difference between List and Set?
The List and Set both extend the collection interface. However, there are some differences between the both
which are listed below.
The List can contain duplicate elements whereas Set includes unique items.
The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection
which does not preserve the insertion order.
The List interface contains a single legacy class which is Vector class whereas Set interface does not have any
legacy class.
The List interface can allow n number of null values whereas Set interface only allows a single null value.
Difference between List and Set
List(Interface) Set (Interface)
1.List is index based data structure . 1.It is not Indexed based data
structure.It store the data accordingly
2.List can store Duplicate element. to the hashcode values.
3.List can store any numbers of null 2.Set does not allow to store duplicate
values(because it allow duplicate element.
value). 3.Set can store only one null
4.List follows the insertion orders. values(because it don’t allow duplicate
value).
5.We can iterate(get) the List element 4.Set does not follows the insertion
b y I t e r a t o r ( F o r w a r d order.
direction)&ListIterator(Forward 5.We can iterate(get) the List element
&backward element can get). by Iterator(Forward direction)
Example of ArrayList(Interface)
• The set interface is inherited from the Java try { Output :[65, 21, 53,
collections Interface A Set interface for (int i = 0; i <= 5; i++) { 22, 23, 43]
cannot store duplicate/redundant elements set.add(count[i]);} The sorted list is:
in it.It store unique values Here’s an [21, 22, 23, 43, 53,
System.out.println(set);
65]
example based on a set interface. TreeSet<Integer> sortedSet = First element of the
package VIPS; new TreeSet<Integer>(set); set is: 21
last element of the
import java.util.*; System.out.println("The sorted list is:");
set is: 65
System.out.println(sortedSet);
public class SetExample {
System.out.println("First element of the set is: " + (Integer)
public static void main(String args[]) { sortedSet.first());
int count[] = { 21, 23, 43, 53, 22, 65 }; System.out.println("last element of the set is: " + (Integer)
sortedSet.last());
Set<Integer> set = new HashSet<Integer>(); } catch (Exception e) {}}}
HashSet:
• Java HashSet class creates a
collection that use a hash table
for storage. Hashset only contain
unique elements and it inherits
the Abstract Set class and
implements Set interface
Map Interface
• A Map is an object that maps keys to import java.util.HashMap;
values. A map cannot contain public class hashmap {
duplicate keys: Each key can map to public static void main(String[] args){
at most one value. It models the HashMap hm=new HashMap();//HasMap store
mathematical function abstraction. value in Key-value pair
hm.put(67, "Shruti");
• The Java platform contains three
hm.put(68, "Komal");
general-purpose Map
hm.put(69, "Yashdeep");
implementations: HashMap,
TreeMap, and LinkedHashMap. System.out.println(hm);
Their behavior and performance are }}
precisely analogous to HashSet, OUTPUT:{67=Shruti, 68=Komal, 69=Yashdeep}
TreeSet, and LinkedHashSet, as
How to reverse ArrayList?
{
import java.util.ArrayList; System.out.println(i.next());
import java.util.Collection; }
import java.util.Collections; Iterator i2 = list.iterator();
hset.add("Ducati"); treeset.add(8476);
hset.add("Yamaha"); treeset.add(748);
hset.add("Yamaha"); treeset.add(88);
hset.add("Suzuki"); treeset.add(983);
hset.add(null); treeset.add(18);
hset.add(null); treeset.add(0);
System.out.println(hset);}} }
OUTPUT: OUTPUT:
[null, Suzuki, Ducati, Yamaha, Kawasaki, Honda] [0, 18, 88, 748, 983, 8476]
How to synchronize List, Set and Map elements?
• Yes, Collections class provides methods to Q What is the advantage of the generic
make List, Set or Map elements as collection?
synchronized: • There are three main advantages of
using the generic collection.
• public static List synchronizedList(List l){}
• public static Set synchronizedSet(Set s){} • If we use the generic class, we don't
need typecasting.
• public static SortedSet
synchronizedSortedSet(SortedSet s){} • It is type-safe and checked at
compile time.
• public static Map synchronizedMap(Map
m){} • Generic confirms the stability of the
code by making it bug detectable at
• public static SortedMap compile time.
synchronizedSortedMap(SortedMap m){}
Q What is hash-collision in Hashtable and • QWhat is the default size of load factor in
how it is handled in Java? hashing based collection?
• Two different keys with the same hash value • The default size of load factor is 0.75. The
are known as hash-collision. Two separate default capacity is computed as initial capacity
entries will be kept in a single hash bucket * load factor. For example, 16 * 0.75 = 12. So,
to avoid the collision. There are two ways to 12 is the default capacity of Map.
avoid hash-collision.
• Separate Chaining • Q What do you understand by fail-fast?
• Open Addressing • The Iterator in java which immediately throws
ConcurrentmodificationException, if any
Q What is the Dictionary class?
structural modification occurs in, is called as a
• The Dictionary class provides the capability Fail-fast iterator. Fail-fats iterator does not
to store key-value pairs. require any extra space in memory.
What is the difference between HashSet and
TreeSet and HashMap?
What is the difference between HashSet and HashMap?
• The HashSet and TreeSet, both classes,
• The differences between the HashSet and HashMap are
implement Set interface. The differences listed below.
between the both are listed below. • HashSet contains only values whereas HashMap includes
the entry (key, value). HashSet can be iterated, but
HashMap needs to convert into Set to be iterated.
• HashSet maintains no order whereas • HashSet implements Set interface whereas HashMap
TreeSet maintains ascending order. implements the Map interface
• HashSet cannot have any duplicate value whereas
• HashSet impended by hash table whereas HashMap can contain duplicate values with unique keys.
TreeSet implemented by a Tree structure. • HashSet contains the only single number of null value
• HashSet performs faster than TreeSet. whereas HashMap can hold a single null key with n
number of null values.
• HashSet is backed by HashMap whereas
TreeSet is backed by TreeMap.
What is the difference between Comparable and
Comparator and Collection and Collections ?
The differences between the Collection and Comparable Comparator
Collections are given below.
more.
System.out.println(Students);
}
}
Java collections: Queue
• The hashCode() method returns the same integer number if two keys (by calling equals()
method) are identical.
• However, it is possible that two hash code numbers can have different or the same keys.
• If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.
Why we override equals() method?
• The equals method is used to check whether two objects are the same
or not. It needs to be overridden if we want to check the objects based
on the property.
• For example, Employee is a class that has 3 data members: id, name,
and salary. However, we want to check the equality of employee
object by the salary. Then, we need to override the equals() method.
How to convert ArrayList to Array and Array to
ArrayList?
• We can convert an Array to ArrayList by using the asList() method of
Arrays class. asList() method is the static method of Arrays class and
accepts the List object. Consider the following syntax:
• Arrays.asList(item)
• We can convert an ArrayList to Array using toArray() method of the
ArrayList class. Consider the following syntax to convert the
ArrayList to the List object.
• List_object.toArray(new String[List_object.size()])
How to make Java ArrayList Read-Only?
Interface. The term Deque stands public class DequeInterface {public static void main(String[] args) {
Deque<Integer> num = new ArrayDeque<>();
for Double-Ended Queue. The num.offer(10);num.offerLast(21);num.offerFirst(52);
Deque supports insertion and System.out.println("Deque elements: " + num);
deletion operations on both sides int first = num.peekFirst();