Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Unit 3 Ajava Collection Frame Work and Generic Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 3 Ajava Collection Frame Work and Generic Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Collection frame work and Generic

Programming
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).
What is a framework in Java

• It provides readymade architecture.


• It represents a set of classes and interfaces.
• It is optional.
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the
Collection framework.
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.
ArrayList
import java.util.ArrayList; System.out.println(Name);
class javaCollections{ Name.add(0,"Amit"); // add rohit in
public static void main(String[] args) second position
{ System.out.println(Name);
ArrayList<String> Name= new Name.remove(1); // remove particular
ArrayList<String>(); index
Name.add("Ankit"); System.out.println(Name);
Name.add("riya"); Name.Set(0,Alfaz); // value replace
Name.add("ansseh"); System.out.println(Name);
System.out.println(Name); System.out.println(Name.get(3));
Name.add("ashutosh"); Name.clear();// remove all elements
System.out.println(Name); System.out.println(Name);
Name.add(1,"Rohit"); // add rohit in }
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.
1.import java.util.*;
2.public class TestJavaCollection2{
3.public static void main(String args[]){
4.LinkedList<String> al=new LinkedList<String>();
5.al.add("Ravi");
6.al.add("Vijay");
7.al.add("Ravi");
8.al.add("Ajay");
9.Iterator<String> itr=al.iterator();
10.while(itr.hasNext()){
11.System.out.println(itr.next());
12.}
13.}
14.}
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.
1.import java.util.*;
2.public class TestJavaCollection3{
3.public static void main(String args[]){
4.Vector<String> v=new Vector<String>();
5.v.add("Ayush");
6.v.add("Amit");
7.v.add("Ashish");
8.v.add("Garima");
9.Iterator<String> itr=v.iterator();
10.while(itr.hasNext()){
11.System.out.println(itr.next());
12.}
13.}
14.}
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.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10.stack.pop();
11.Iterator<String> itr=stack.iterator();
12.while(itr.hasNext()){
13.System.out.println(itr.next());
14.}
15.}
16.}
Q. Write a Java program to sort a given array list.
import java.util.*;
public class E {
public static void main(String[] args)
{ // Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println("List before sort: "+list_Strings);
Collections.sort(list_Strings);
System.out.println("List after sort: "+list_Strings); } }
Q. Write a Java program to reverse elements in an array list.
import java.util.*;
public class Exercise11 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println("List before reversing :\n" + list_Strings);
Collections.reverse(list_Strings);
System.out.println("List after reversing :\n" + list_Strings);
}
}
Generics in Java
Generics allow our classes interfaces or methods o be parameterized
with type information.
It allows us to pass some type information to our classes or interfaces
so that they can be used with different types of data.
Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns


some value after performing a task. It is exactly like a normal function,
however, a generic method has type parameters that are cited by actual
type.
Generic Classes: A generic class is implemented exactly like a non-
generic class. The only difference is that it contains a type parameter
section. There can be more than one type of parameter, separated by a
comma. The classes, which accept one or more parameters, ?are known
as parameterized classes or parameterized types.
// Java program to show working of user defined
// Generic classes
// Driver class to test above
// We use < > to specify Parameter type class Main {
class Test<T> { public static void main(String[] args)
// An object of type T is declared {
T obj; // instance of Integer type
Test(T obj) { Test<Integer> iObj = new
this.obj = obj; Test<Integer>(15);
} // constructor System.out.println(iObj.getObject());
public T getObject() { return this.obj; }
} // instance of String type
Test<String> sObj
Output = new Test<String>(“Generic");
15 System.out.println(sObj.getObject());
Generic }
}
We can also pass multiple Type parameters in Generic classes.

// Java program to show multiple System.out.println(obj2); }


// type parameters in Java Generics }
// We use < > to specify Parameter type // Driver class to test above
class Test<T, U> class Main
{T obj1; // An object of type T {
U obj2; // An object of type U public static void main (String[] args)
// constructor {
Test(T obj1, U obj2) Test <String, Integer> obj =
{ new Test<String,
this.obj1 = obj1; Integer>(“ABC", 15);
this.obj2 = obj2; }
// To print objects of T and U obj.print();
public void print() }
Type Parameters in Java Generics
The type parameters naming conventions are important to learn generics
thoroughly. The common type parameters are as follows:
• T – Type
• E – Element
• K – Key
• N – Number
• V – Value
// Java program to illustrate Generic for loop // returns the sum of array elements
public static int sum(int arr[])
import java.io.*; {

class GenericsForLoopExample { // initialize the sum variable


int sum = 0;
public static void main(String[] args)
{ // generic for loop where var stores the integer
// create an array // value stored at every index of array
int arr[] = { 120, 100, 34, 50, 75 }; for (int var : arr) {
sum += var;
// get the sum of array elements }
int s = sum(arr);
return sum;
// print the sum }
System.out.println(s); }
}
Map Interface in Java

• 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).
Methods in Java Map Interface

clear() This method is used in Java Map Interface to clear and remove all of
the elements or mappings from a specified Map collection

This method is used in Map Interface in Java to check whether a


particular key is being mapped into the Map or not. It takes the
containsKey(Object)
key element as a parameter and returns True if that element is
mapped in the map.

This method is used to retrieve or fetch the value


mapped by a particular key mentioned in the
get(Object) parameter. It returns NULL when the map contains no
such mapping for the key
// Java Program to Demonstrate // using put() method
// Working of Map interface hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
// Importing required classes hm.put("c", new Integer(300));
import java.util.*; hm.put("d", new Integer(400));

// Main class for (Map.Entry<String, Integer> me :


class GFG { hm.entrySet()) {

// Main driver method // Printing keys


public static void main(String args[])
{ System.out.print(me.getKey() + ":");
// Creating an empty HashMap
System.out.println(me.getValue());
Map<String, Integer> hm = new
HashMap<String, Integer>(); }
}
// Inserting pairs in above Map }
HashMap

It 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. This class uses a technique called Hashing.
// Java Program to illustrate the Hashmap Class // Inserting entries in the Map
// using put() method
// Importing required classes map.put("vishal", 10);
import java.util.*; map.put("sachin", 30);
map.put("vaibhav", 20);
// Main class
public class GFG { // Iterating over Map
for (Map.Entry<String, Integer> e :
// Main driver method map.entrySet())
public static void main(String[] args)
{ // Printing key-value pairs
System.out.println(e.getKey()
+""
// Creating an empty HashMap
+ e.getValue());
Map<String, Integer> map = new
HashMap<>(); }
}
LinkedHashMap
It is just like HashMap with the additional feature of maintaining an
order of elements inserted into it. HashMap provided the advantage of
quick insertion, search, and deletion but it never maintained the track
and order of insertion which the LinkedHashMap provides where the
elements can be accessed in their insertion order
// Java Program to Illustrate the LinkedHashmap // Inserting pair entries in above
Class Map
// using put() method
// Importing required classes map.put("vishal", 10);
import java.util.*; map.put("sachin", 30);
map.put("vaibhav", 20);
// Main class
public class GFG { // Iterating over Map
for (Map.Entry<String, Integer> e :
// Main driver method map.entrySet())
public static void main(String[] args)
{ // Printing key-value pairs
System.out.println(e.getKey()
+""
// Creating an empty
LinkedHashMap +
e.getValue());
Map<String, Integer> map = new
LinkedHashMap<>(); }
}
Generic Constructors and Interfaces
Generic constructors are the same as generic methods. For generic
constructors after the public keyword and before the class name the type
parameter must be placed. Constructors can be invoked with any type
of a parameter after defining a generic constructor.
class Main { }
public static void main(String[] args) {
// create a generics class
// initialize generic class class GenericsClass<T> {
// with Integer data
GenericsClass<Integer> intObj = new // variable of T type
GenericsClass<>(5); private T data;
System.out.println("Generic Class returns: " +
intObj.getData());
public GenericsClass(T data) {
this.data = data;
// initialize generic class
}
// with String data
GenericsClass<String> stringObj = new
GenericsClass<>("Java Programming"); // method that return T type variable
System.out.println("Generic Class returns: " + public T getData() {
stringObj.getData()); return this.data;
} }
}
Bounded Types in Java
A bounded type parameter is a generic type that is restricted to a specific
subset of types. It can be defined using the extends keyword followed
by the upper bound. The upper bound can be a class or an interface, and
it indicates that the generic type must be a subclass of the specified class
or implement the specified interface.
Syntax:
The syntax for defining a bounded type parameter is as follows:
{
class Bound<T extends A> public void displayClass()
{ private T objRef; {
public Bound(T obj) System.out.println("Inside sub class C");
this.objRef = obj; }
} }
public void doRunTest(){ public class BoundedClass
this.objRef.displayClass(); {
} public static void main(String a[])
} {
class A
{ public void displayClass() Bound<C> bec = new Bound<C>(new C());
{ bec.doRunTest();
System.out.println("Inside super class A");
} } Bound<B> beb = new Bound<B>(new B());
class B extends A beb.doRunTest();
{
public void displayClass() Bound<A> bea = new Bound<A>(new A());
{ bea.doRunTest();
System.out.println("Inside sub class B");
} } }
}
Wildcards in Java
The question mark (?) is known as the wildcard in generic
programming. It represents an unknown type. The wildcard can be used
in a variety of situations such as the type of a parameter, field, or local
variable; sometimes as a return type. Unlike arrays, different
instantiations of a generic type are not compatible with each other, not
even explicitly. This incompatibility may be softened by the wildcard
if ? is used as an actual type parameter.
Types of wildcards in Java
1. Upper Bounded Wildcards
2. Lower Bounded Wildcards
3. Unbounded Wildcards
Upper Bounded Wildcards:
These wildcards can be used when you want to relax the restrictions on
a variable. For example, say you want to write a method that works on
List < Integer >, List < Double >, and List < Number >, you can do this
using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’),
followed by the extends keyword, followed by its upper bound.
// Java program to demonstrate Upper Bounded
Wildcards // printing the sum of elements in list
System.out.print("Total sum is:" + sum(list2));
import java.util.Arrays; }
import java.util.List;
private static double sum(List<? extends
class WildcardDemo { Number> list)
public static void main(String[] args) {
{ double sum = 0.0;
for (Number i : list) {
// Upper Bounded Integer List sum += i.doubleValue();
List<Integer> list1 = Arrays.asList(4, 5, 6, 7); }

// printing the sum of elements in list return sum;


System.out.println("Total sum is:" + sum(list1)); }
}
// Double list
List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1);
Lower Bounded Wildcards:
It is expressed using the wildcard character (‘?’), followed by the super
keyword, followed by its lower bound: <? super A>.

You might also like