VIPS OOPS Unit 2 Collection API Interface
VIPS OOPS Unit 2 Collection API Interface
Nishtha Kansal
Assistant Professor
VIPS
What are Java collections?
• Java collections refer to a
collection of individual objects
that are represented as a single
unit. You can perform all
operations such as searching,
sorting, insertion, manipulation,
deletion, etc., on Java collections
just like you do it on data.
• Java collection it is a single
entity object which can store
multiple data.
Collections In Java and How to Implement Them?
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 LinkedList is better to manipulate data.
data.
ArrayList provides random access. LinkedList does not provide random
access.
ArrayList takes less memory overhead as LinkedList takes more memory
it stores only object overhead, 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
compulsory for them to make an instance of the to its numerous advantages. The advantages
Iterator interface from the collection of objects
they desire to traverse over. After that, the received of Java Iterator are given as follows -
Iterator maintains the trail of the components in • The user can apply these iterators to any of
the underlying collection to make sure that the user the classes of the Collection framework.
will traverse over 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
traversing over an Iterator leading to that cannot modernize(add/remove) the
collection, then the Iterator will typically Collection, whereas, if they use the Java
acknowledge it and will throw an exception in the Iterator, they can simply update the
next time when the user will attempt to get the next Collection.
component from the Iterator.
Disadvantages of Java Iterator
Despite the numerous advantages, the Java Iterator has
various disadvantages also. The disadvantages of the Java
• Java Iterator Methods
Iterator are given below -
• The following figure perfectly
• The Java Iterator only preserves the iteration in the displays the class diagram of the
forward direction. In simple words, the Java Iterator is a
uni-directional Iterator.
Java Iterator interface. It contains
• The replacement and extension of a new component are a total of four methods that are:
not approved by the Java Iterator.
• In CRUD Operations, the Java Iterator does not hold the
various operations like CREATE and UPDATE.
• In comparison with the Spliterator, Java Iterator does not • hasNext()
support traversing elements in the parallel pattern which
implies that Java Iterator supports only Sequential • next()
iteration.
• In comparison with the Spliterator, Java Iterator does not • remove()
support 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
was added in the Java 8. Let's parameter. It returns E, i.e., the next
discuss each method in detail. element in the traversal. If the iteration or
collection of objects has no more elements
left to iterate, then it throws the
• boolean hasNext(): The method NoSuchElementException.
does not accept any parameter. It • default void remove(): This method also
does not require any parameters. There is
returns true if there are more no return type of this method. The main
elements left in the iteration. If function of this method is to remove the
there are no more elements left, last element returned by the iterator
then it will return false. traversing through the underlying
collection.
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() + " ");
{
ArrayList<String> cityNames = new ArrayList<String>();
System.out.println();
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
shrink its size. Unlike array, we can store n- • It is similar to the ArrayList, but with
number of elements in it as there is no size limit. It two differences-
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
• It is recommended to use the Vector class in the
thread-safe implementation only. If you don't need
collections framework.
to use the thread-safe implementation, you should • Java Vector class Declaration
use the ArrayList, the ArrayList will perform better
in such case. • public class Vector<E>
• The Iterators returned by the Vector class are fail- • extends Object<E>
fast. In case of concurrent modification, it fails and
throws the ConcurrentModificationException. • implements List<E>, Cloneable,
Serializable
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");
public static void vec.addElement("Deer");
main(String args[]) {
//Create a vector
System.out.println("Elements
Vector<String> vec = are: "+vec);
new Vector<String>(); }
//Adding elements using }
add() method of List • Output:
vec.add("Tiger"); • Compile by: javac VectorExample.java
vec.add("Lion");
• Run by: java VectorExample
vec.add("Dog");
vec.add("Elephant"); • Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Vector Example Output:
//Display the vector elements Values in vector: [100,
System.out.println("Values in vector: " +in);
200, 300, 200, 400, 500,
//use remove() method to delete the first occurence of an element
import java.util.*; System.out.println("Remove first occourence of element 200: 600, 700]
public class VectorExample2 { "+in.remove((Integer)200)); Remove first occourence
public static void main(String args[]) {
//Display the vector elements afre remove() method of element 200: true
System.out.println("Values in vector: " +in); Values in vector: [100,
//Create an empty Vector //Remove the element at index 4
System.out.println("Remove element at index 4: "
300, 200, 400, 500, 600,
Vector<Integer> in = new Vector<>(); +in.remove(4)); 700]
//Add elements in the vector System.out.println("New Value list in vector: " +in); Remove element at index
//Remove an element 4: 500
in.add(100); in.removeElementAt(5);
//Checking vector and displays the element
New Value list in vector:
in.add(200);
System.out.println("Vector element after removal: " +in); [100, 300, 200, 400, 600,
in.add(300); //Get the hashcode for this vector 700]
in.add(200); System.out.println("Hash code of this vector = "+in.hashCode()); Vector element after
//Get the element at specified index
in.add(400); System.out.println("Element at index 1 is = "+in.get(1));
removal: [100, 300, 200,
in.add(500); } } 400, 600]
Hash code of this vector
in.add(600);
= 130123751
in.add(700); Element at index 1 is =
300
Enumerated data type
• The Enum in Java is a data type which • Java Enum internally inherits the
contains a fixed set of constants.
Enum class, so it cannot inherit
• It can be used for days of the week
any other class, but it can
(SUNDAY, MONDAY, TUESDAY, implement many interfaces. We
WEDNESDAY, THURSDAY, FRIDAY, and can have fields, constructors,
SATURDAY) , directions (NORTH, methods, and main methods in
SOUTH, EAST, and WEST), season
(SPRING, SUMMER, WINTER, and Java enum.
AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc. According to the Java naming
conventions, we should have all constants in
capital letters. So, we have enum constants
in capital letters.
Points to remember for Java Enum
Enum improves type safety class EnumExample1{
Enum can be easily used in //defining the enum inside the class
switch public enum Season { WINTER,
SPRING, SUMMER, FALL }
Enum can be traversed
//main method
Enum can have fields,
public static void main(String[] args) {
constructors and methods
//traversing the enum
Enum may implement many
for (Season s : Season.values())
interfaces but cannot extend any
class because it internally System.out.println(s);
Output:WINTER
SPRING
extends Enum class }} SUMMER
FALL
Enum – Enumeration in Java Example
• An enumeration (enum for short) Here's an example:
enum Colors {
in Java is a special data type RED,
which contains a set of BLUE,
predefined constants. YELLOW,
GREEN
• How to Create an Enum in Java }
• To create an enum, we use the In the code above, we created an enum called
Colors. You may notice that the values of this
enum keyword, similar to how enum are all written in uppercase – this is just a
you'd create a class using the general convention. You will not get an error if
the values are lowercase.
class keyword. Each value in an enum is separated by a
comma.Next, we're going to create a new variable
and assign one of the values of our enum to it.
Enum example:
enum Colors { • This is similar to initializing any
RED,
BLUE,
other variable. In the code above,
YELLOW, we initialized a Colors variable
GREEN and assigned one of the values of
}public class Main { an enum to it using the dot
public static void main(String[] args) {
syntax: Colors red =
Colors red = Colors.RED;
Colors.RED;.
System.out.println(red);
// RED
}
}
Enum ordinal()function
enum Colors { • // 0
RED, • }
BLUE,
•}
YELLOW,
GREEN
Output :red.ordinal() from the
code above returns 0.
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red.ordinal());
How to Use an Enum in a Switch
Statement
• In this section, we'll se how we can use an enum in a case BLUE:
switch statement.
System.out.println("The color is blue");
• Here is an example:
break;
public class Main {
case YELLOW:
enum Colors {
RED, System.out.println("The color is yellow");
BLUE, break;
YELLOW, case GREEN:
GREEN System.out.println("The color is green");
} break;
public static void main(String[] args) { }
Colors myColor = Colors.YELLOW; }
switch(myColor) { }
case RED: This is a very basic example of how we can use an enum
System.out.println("The color is red"); in a switch statement. We would get "The color is
yellow" printed to the console because that is the only
break; case that matches the switch statement's condition.
How to Loop Through the Values of an Enum
enum in Java has a values() method that returns an array of the values
of an enum. We're going to use a for-each loop to iterate through and /*
print the values of our enum.
RED
Here's how we can do that: BLUE
enum Colors {
YELLOW
RED,
BLUE, GREEN
YELLOW,
*/
GREEN
public class Main { }
public static void main(String[] args) {
for (Colors allColors : Colors.values()) {
System.out.println(allColors);
}
}
Conclusion
• In this ,we got to know what an
enum is in Java,
I
how to create it,
and how to assign its values to
other variables.
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 to the hashcode
2.List can store Duplicate element. 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
by Iterator(Forward 4.Set does not follows the insertion order.
direction)&ListIterator(Forward 5.We can iterate(get) the List element by
&backward element can get). 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 The sorted list is:
set.add(count[i]);} [21, 22, 23, 43, 53,
in it.It store unique values Here’s an 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
import java.util.*; last element of the
System.out.println("The sortedset listis:is:");
65
public class SetExample { System.out.println(sortedSet);
public static void main(String args[]) { System.out.println("First element of the set
is: " + (Integer) sortedSet.first());
int count[] = { 21, 23, 43, 53, 22, 65 };
System.out.println("last element of the set
Set<Integer> set = new HashSet<Integer>(); is: " + (Integer) sortedSet.last());
} 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
mathematical function abstraction. store value in Key-value pair
• The Java platform contains three hm.put(67, "Shruti");
general-purpose Map hm.put(68, "Komal");
implementations: HashMap, hm.put(69, "Yashdeep");
TreeMap, and LinkedHashMap. System.out.println(hm);
Their behavior and performance are }}
precisely analogous to HashSet, OUTPUT:{67=Shruti, 68=Komal,
TreeSet, and LinkedHashSet, as 69=Yashdeep}
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();
Collections.reverse(list);
import java.util.Iterator;
System.out.println("printing list in reverse order....");
import java.util.List;
public class ReverseArrayList { while(i2.hasNext())
public static void main(String[] args) { {
List list = new ArrayList<>(); System.out.println(i2.next());
} } }
list.add(10);
Outputprinting the list....
list.add(50);
10
list.add(30); 50
Iterator i = list.iterator(); 30
System.out.println("printing the list...."); printing list in reverse order....
while(i.hasNext()) 30 50 10
Hashset and Treeset example TreeSet Class is a NavigableSet implementation based on TreeMap. Here, the elements are
package VIPS; ordered using comparators.
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
• public static SortedSet need typecasting.
synchronizedSortedSet(SortedSet s){}
• public static Map synchronizedMap(Map
• It is type-safe and checked at compile
m){} time.
• public static SortedMap • Generic confirms the stability of the
synchronizedSortedMap(SortedMap m){} code by making it bug detectable at
compile time.
Q What is hash-collision in Hashtable • QWhat is the default size of load factor in
and how it is handled in Java? hashing based collection?
• Two different keys with the same hash • The default size of load factor is 0.75. The
value are known as hash-collision. Two default capacity is computed as initial
separate entries will be kept in a single capacity * load factor. For example, 16 *
0.75 = 12. So, 12 is the default capacity of
hash bucket to avoid the collision. There Map.
are two ways to avoid hash-collision.
• Separate Chaining
• Q What do you understand by fail-fast?
• Open Addressing • The Iterator in java which immediately
Q What is the Dictionary class? throws ConcurrentmodificationException, if
• The Dictionary class provides the any structural modification occurs in, is
called as a Fail-fast iterator. Fail-fats iterator
capability to store key-value pairs. does not require any extra space in memory.
What is the difference between HashSet and TreeSet and HashMap?
• 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?