Dhdfs
Dhdfs
➢ Collection overview
➢ Collection interface - List, Set, Map
➢ Collection Classes - ArrayList, HashSet, HashMap
➢ Iterator-For-Each-Comparators
➢ Wrapper classes
➢ Motivation for Generic Programming – Generic Classes and Methods – Bounded
Types –Wildcard Arguments –Generic Constructors and Interfaces.
Arrays vs Collections
Collection & Collection Framework
● A Collection represents a group of individual objects that represent a single entity
2 public boolean addAll(Collection<? extends It is used to insert the specified collection elements in the invoking
E> c) collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified collection from the
invoking collection.
5 default boolean removeIf(Predicate<? super It is used to delete all the elements of the collection that satisfy the
E> filter) 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.
Iterators
● Iterators in Java are used in the Collection framework to retrieve elements one by one.
● It is a universal iterator as we can apply it to any Collection object.
● By using Iterator, we can perform both read and remove operations.
1 public boolean hasNext() It returns true if the iterator has more elements otherwise it returns 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.
Collections class
● Collections class is one of the utility classes in Java Collections Framework.
● The Collections class is present in the java.util package.
● Java Collections class is used with the static methods that operate on the collections
or return the collection.
● All the methods of this class throw the NullPointerException if the collection or
object passed to the methods is null.
Collection Class declaration
● The syntax of the Collection class declaration is mentioned below:
public class Collections extends Object
List
● It is a child interface of the collection interface.
● This interface is dedicated to the data of the list type in which we can store all the
ordered collections of the objects.
● It also allows duplicate data to be present in it.
● The list interface is implemented by various classes like ArrayList, Vector, Stack,
etc.
● Since all the subclasses implement the list, we can instantiate a list object with any
of these classes.
● For example:
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
Operations in a Java List Interface
● Since List is an interface, it can be used only with a class that implements this
interface.
● Some methods that frequently used on the List:
○ add(): used to add the elements to List class
○ set(): used to update the elements in List class
○ indexOf() / lastIndexOf: used to search for elements in List class
○ remove(): used to remove the elements from List class
○ get(): used to access the elements in List class
○ contains(): used to check if an element is present in the List class
ArrayList
● ArrayList provides us with dynamic arrays in Java.
● The size of an ArrayList is increased automatically if the collection grows or shrinks
if the objects are removed from the collection.
● Java ArrayList allows us to randomly access the list.
● ArrayList can not be used for primitive types, like int, char, etc. We will need a
wrapper class for such cases.
● Though, it may be slower than standard arrays but can be helpful in programs where
lots of manipulation in the array is needed.
Example 1
import java.io.*;
import java.util.*;
class ArrayListTest {
public static void main(String[] args) {
// Printing elements
System.out.println(al);
// Now remove element from the above list present at 1st index
al.remove(1);
al.remove("Object"); // Now remove the current object from the updated List
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value
HashSet.
3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given integer value
4) HashSet(Collection<? extends E> c) It is used to initialize the hash set by using the elements of the collection c.
Example 1
import java.util.*;
class SetExample2 {
public static void main(String[] args) {
// Creating object of Set of type String
Set<String> h = new HashSet<String>();
// Adding elements into the HashSet using add() method
h.add("India");
h.add("Australia");
h.add("South Africa");
h.add("India");
// Displaying the HashSet
System.out.println(h);
// Removing items from HashSet using remove() method
h.remove("Australia"); //value
System.out.println("Set after removing " + "Australia:" + h);
// Iterating over hash set items
System.out.println("Iterating over set:");
// Iterating through iterators
Iterator<String> i = h.iterator();
// It holds true till there is a single element remaining in the object
while (i.hasNext())
System.out.println(i.next());
}
}
Example 1
import java.util.*;
class SetExample2 {
public static void main(String[] args) {
// Creating object of Set of type String
Set<String> h = new HashSet<String>();
// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set"); Output
System.out.println(intersection); Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8,
9]
// To find the symmetric difference
Set<Integer> difference = new HashSet<Integer>(a);
Intersection of the two Set[0, 1, 3, 4]
difference.removeAll(b); Difference of the two Set[2, 8, 9]
System.out.print("Difference of the two Set");
System.out.println(difference);
}
}
Map
● Map represents a mapping between a key and a value.
● Java Map interface is not a subtype of the Collection interface. Therefore it behaves a
bit differently from the rest of the collection types.
● Maps are perfect to use for key-value association mapping such as dictionaries.
● The maps are used to perform lookups by keys or when someone wants to retrieve
and update elements by keys.
● Some common scenarios are as follows:
○ A map of error codes and their descriptions.
○ A map of zip codes and cities.
○ A map of managers and employees. Each manager (key) is associated with a list
of employees (value) he manages.
○ A map of classes and students. Each class (key) is associated with a list of
students (value).
HashMap
● HashMap provides the basic implementation of the Map interface of Java.
● It stores the data in (Key, Value) pairs.
● To access a value one must know its key.
● It uses a technique called Hashing to store the data.
Iterating over a Map
● We cannot iterate a Map directly using iterators, because Map are not Collection.
class HashMapExample {
public static void main(String args[]) {
// Creating an empty HashMap
Map<String, Integer> hm = new HashMap<String, Integer>();
class HashMapExample {
public static void main(String args[]) {
// Creating an empty HashMap
Map<String, Integer> hm = new HashMap<String, Integer>();
// Initial Map
System.out.println("Initial Map " + hm1);
// Initial Map
System.out.println("Initial Map " + hm1); Output:
Initial Map {1=VIT, 2=AP, 3=Amaravati}
hm1.put(2, "Andhra Pradesh");
hm1.remove(3); //key
1 : VIT
for (Map.Entry mapElement : hm1.entrySet()) { 2 : Andhra Pradesh
int key = (int)mapElement.getKey();
// Finding the value
String value = (String)mapElement.getValue();
System.out.println(key + " : " + value);
}
}
}
Example 3
import java.util.*;
class Hash2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"vijay");
map.put(4,"umesh");
map.put(2,"ankit");
//Map.Entry for Set and Iterator
Set<Map.Entry<Integer,String>> set=map.entrySet();
Output
Iterator<Map.Entry<Integer,String>> itr=set.iterator();
while(itr.hasNext()) { 1 vijay
2 ankit
Map.Entry e=itr.next();//no need to typecast
4 umesh
System.out.println(e.getKey()+" "+e.getValue());
}
}
}
Collection vs Collections
● Collection is an interface which can be used to represent a group of individual objects
as a single entity.
● Contains the most common methods which are applicable to any Collection object
class WrapperClassExample1 {
public static void main(String[] args) {
// In java, in case of floating values they are stored as x = (y)f
// Conversion of float value to int
Float floatWrap = Float.valueOf(45.158f);
// Invoking the intValue() method over the stored float value to store
int floatToInt = floatWrap.intValue();
class ArrayListTest {
public static void main(String[] args) {
al.add("Rajesh" );
al.add("Rahul" );
al.add(101 );
al.add(45.67 );
System.out.println(al);
}
}
Example 1
import java.io.*;
import java.util.*;
class ArrayListTest {
public static void main(String[] args) {
al.add( "Rajesh");
al.add( "Rahul");
al.add( 101);
al.add( 45.67);
System.out.println(al);
}
}
Output
[Rajesh, Rahul, 101, 45.67]
Why Generics
Type-safety:
● We can hold only a single type of objects in generics.
● It doesn't allow to store other objects.
● The ‘T’ type indicates that it can refer to any type (like String, Integer, and Employee). The type you
specify for the class will be used to store and retrieve the data.
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
Example 1
// We use < > to specify Parameter type
class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}
class Main {
public static void main(String[] args) {
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15); Output
System.out.println(iObj.getObject()); 15
OOPs
// instance of String type
Test<String> sObj = new Test<String>("OOPs");
System.out.println(sObj.getObject());
}
}
Example 2
class MyGen<T> {
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
class TestGenerics {
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
m.add(2);
m.add("vivek");
System.out.println(m.get());
}
}
Example 2
class MyGen<T> {
T obj;
void add(T obj){
this.obj=obj;
}
T get(){
return obj;
}
}
class TestGenerics {
public static void main(String args[]){ Output
MyGen<Integer> m=new MyGen<Integer>();
m.add(2); Compile time error
m.add("vivek");
System.out.println(m.get());
}
}
Example 3
public class AddNumbers<T extends Number> {
T num1, T num2;
public AddNumbers(T num1, T num2) {
this.num1 = num1;
this.num2 = num2;
}
public T add() {
if (num1 instanceof Integer) {
return (T) (Integer) (num1.intValue() + num2.intValue());
} else if (num1 instanceof Double) {
return (T) (Double) (num1.doubleValue() + num2.doubleValue());
} else { return null; }
}
public static void main(String[] args) {
AddNumbers<Integer> intAdder = new AddNumbers<>(2, 3);
Integer intResult = intAdder.add();
System.out.println("Integer Result: " + intResult);
AddNumbers<Double> doubleAdder = new AddNumbers<>(2.5, 3.5);
Double doubleResult = doubleAdder.add();
System.out.println("Double Result: " + doubleResult);
}
}
Example 3
public class AddNumbers<T extends Number> {
T num1, T num2;
public AddNumbers(T num1, T num2) {
this.num1 = num1;
this.num2 = num2;
}
public T add() {
if (num1 instanceof Integer) {
return (T) (Integer) (num1.intValue() + num2.intValue());
} else if (num1 instanceof Double) {
return (T) (Double) (num1.doubleValue() + num2.doubleValue());
} else { return null; }
}
public static void main(String[] args) {
AddNumbers<Integer> intAdder = new AddNumbers<>(2, 3); Output:
Integer intResult = intAdder.add();
System.out.println("Integer Result: " + intResult); Integer Result: 5
AddNumbers<Double> doubleAdder = new AddNumbers<>(2.5, 3.5); Double Result: 6.0
Double doubleResult = doubleAdder.add();
System.out.println("Double Result: " + doubleResult);
}
}
Example 4
public class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
public static void main(String[] args) {
Pair<Integer, String> intStrPair = new Pair<>(10, "hello");
System.out.println("First Value: " + intStrPair.getFirst());
System.out.println("Second Value: " + intStrPair.getSecond());
Pair<Double, Character> doubleCharPair = new Pair<>(3.14, 'a');
System.out.println("First Value: " + doubleCharPair.getFirst());
System.out.println("Second Value: " + doubleCharPair.getSecond());
}
}
Example 4
public class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
public static void main(String[] args) {
Pair<Integer, String> intStrPair = new Pair<>(10, "hello");
Output:
System.out.println("First Value: " + intStrPair.getFirst());
System.out.println("Second Value: " + intStrPair.getSecond()); First Value: 10
Pair<Double, Character> doubleCharPair = new Pair<>(3.14, 'a'); Second Value: hello
System.out.println("First Value: " + doubleCharPair.getFirst()); First Value: 3.14
System.out.println("Second Value: " + doubleCharPair.getSecond()); Second Value: a
}
}
Generic Method
● Like the generic class, we can create a generic method that can accept any type of
arguments.
● It is exactly like a normal function, however, a generic method has type parameters
that are cited by actual type. This allows the generic method to be used in a more
general way.
● The type parameter must be placed after the public/static keyword and before the
return type of generic method.
● Here, the scope of arguments is limited to the method where it is declared.
● It allows static as well as non-static methods.
Example 1
class Test {
class GenericConstructor {
private double v;
// Constructor of this class where T is typename and t is object
<T extends Number> GenericConstructor(T t) {
// Converting input number type to double using the doubleValue() method
v = t.doubleValue();
}
void show() {
System.out.println( "v: " + v);
}
}
class GenericConstructor {
public static void main(String[] args) {
System.out.println( "Number to Double Conversion:" );
// Creating objects of type GenericConstructor
GenericConstructor obj1 = new GenericConstructor( 10);
GenericConstructor obj2 = new GenericConstructor( 136.8F);
obj1.show(); Output
obj2.show(); Number to Double Conversion:
} v: 10.0
} v: 136.8000030517578
Generic Interfaces
● Generic Interfaces in Java are the interfaces that deal with different data types.
● It allows putting constraints i.e. bounds on data types for which interface is
implemented.
Syntax:
interface interface-Name < type-parameter-list > {//....}
Output:
Before Sorting: [Name: John, Age: 20, Name: Mary, Age: 25, Name: David, Age: 18, Name: Sarah, Age: 22]
After Sorting: [Name: David, Age: 18, Name: John, Age: 20, Name: Sarah, Age: 22, Name: Mary, Age: 25]