Date post: | 30-May-2018 |
Category: |
Documents |
Upload: | suresh1130 |
View: | 222 times |
Download: | 0 times |
of 37
8/14/2019 11 2 Collections and Generics
1/37
1Java
Generics and Collection
Part 1
8/14/2019 11 2 Collections and Generics
2/37
2Java
Revisit :converting Collection into arrays11
Y10
Y
8/14/2019 11 2 Collections and Generics
3/37
3Java
Summary of valid and invalid generic assignments18
Restricting to certain types17
Defined generic method 16
User defined generic class15
Code snippet of List interface14
Identifying a generic class13
Creating your own generic class and generic methods12
Contents
8/14/2019 11 2 Collections and Generics
4/37
4Java
Know
What generics is about Type Erasure
How to creating generic classes
8/14/2019 11 2 Collections and Generics
5/37
5Java
Be able to
Use generics Create your own generic class
8/14/2019 11 2 Collections and Generics
6/37
6Java
Motivation behind generics
import java.util.*;class Test{ public static void main(String[] s){ ArrayList a= new ArrayList();
a.add(1);a.add("Mary");a.add(1.78);
for(Object o:a)System.out.println(o);} }
Allows you to add any kind of object
Primary reason why generics came in
Integer i=(Integer)a.get(1);
Explicit cast required
Example 1
8/14/2019 11 2 Collections and Generics
7/37
7Java
Creating type-safe collectionsimport java.util.*;class Test{
public static void main(String[] s){ ArrayList a= new
ArrayList () ;a.add(1);a.add(2);a.add(3);for( int o:a)System.out.println(o);} }
Allows you to add only integers
unboxing
int i=((Integer)a.get(1)).intValue();
Example 2
8/14/2019 11 2 Collections and Generics
8/37
Is an instance of ArrayListsame as instance of ArrayList ?
In terms of what both theinstances hold-they aresame, but the compiler
treats generics verydifferently from non-generic
collection. MeaningArrayList and
ArrayList are not exactlysame. We will see this
8/14/2019 11 2 Collections and Generics
9/37
9Java
Type Erasure
Generics are implemented by type erasure :generic type information is present only atcompile time, after which it is erased by the
compiler. Which means that the ArrayList
becomes ArrayList at runtime.
8/14/2019 11 2 Collections and Generics
10/37
10Java
Mixing generics and legacy
codeLegal Code: ArrayList a= new ArrayList(); ArrayList a= new ArrayList(); List a= new ArrayList(); List a= new ArrayList(); List a= new ArrayList();
8/14/2019 11 2 Collections and Generics
11/37
11Java
The compiler allowsthis so that the legacycode which was
written in the good old java days also works
with generics. At first itmay sound good. But
there are someundesirable
consequences whichwe must be aware of.An example of such aconsequence is in the
next slide.
8/14/2019 11 2 Collections and Generics
12/37
12Java
Consequences of mixing code
import java.util.*;class Test{
public static void main(String[] s){
ArrayList a=new ArrayList();
a.add(1);a.add(1.1);
ArrayList b=a;
for(Integer i:b)
System.out.println(i);}}
java.lang.ClassCastException: java.lang.Double at runtime
Example 3
8/14/2019 11 2 Collections and Generics
13/37
13Java
Another such situation would be :
List l= new ArrayList();
l.add(AbC);
Perfectly valid code! No compile-time or runtimeerrors. Only a warning is generated.
Both the examples lead to incorrect situations.Thatis the reason why a warning is generated by the
compiler when you add or manipulate the elementsusing non-type safe collections.
8/14/2019 11 2 Collections and Generics
14/37
14Java
Generics and polymorphism
List a= new ArrayList();
List a= new ArrayList();
WHY ?
8/14/2019 11 2 Collections and Generics
15/37
15Java
Number
Integer Double
Hypothesis :List a= new ArrayList(); is valid.
Assume the following code snippet: ArrayList a= new ArrayList();
a.add(1); m(a);}
static void m(List n){
Double d=3.4;
n.add(d); ..}
Valid as per hypothesis
Oops! we just added a double
into an Integer collection
8/14/2019 11 2 Collections and Generics
16/37
16Java
Could the compiler have generated a warning? Assuming that hypothesis is correct, every part of the code is legal. Answer is NO.Could the runtime system know? NO. Runtime system does not have any
information about type of collection (type erasure).For the runtime system List is just Listand ArrayList is just ArrayList.Conclusion: The hypothesis is incorrect.
List a= new ArrayList(); isnot valid .
8/14/2019 11 2 Collections and Generics
17/37
17Java
How was it alright with arrays? Number n[]= new Integer[3]; is Ok ButArrayList n= newArrayList is not ok.
Let us compile and executea code involving arrays
before I comment on it.
8/14/2019 11 2 Collections and Generics
18/37
18Java
class Test{
public static void main(String[] s){
Number n[]= new Integer[5];
n[0]=1;
n[1]=2;
m(n); }
static void m(Number[] l){
l[3]=3.4; }} No errors at compile time. Runtime error:java.lang.ArrayStoreException:java.lang.Double
legal
Example 4
8/14/2019 11 2 Collections and Generics
19/37
19Java
Compare the two cases(array and collection) andtry to answer how they are
different! Are you telling us that acollection can either hold any
type of data or strictly onlysingle type of data- Integer
means only Integers, Number means only numbers good
bye to polymorphism !
No ! Java designersdid find a way towork around this
problem. Go ahead.
8/14/2019 11 2 Collections and Generics
20/37
20Java
Wild card characters Y
where Y is any collection class thatimplements Collection interface or Map(we are concentrating only on collection withgenerics here )andX is any class or an interface.
8/14/2019 11 2 Collections and Generics
21/37
21Java
Y
8/14/2019 11 2 Collections and Generics
22/37
22Java
import java.util.*;
class Test{
public static void main(String[] s){
ArrayList l=newArrayList();
l.add(1);
l.add(2);
ArrayList
8/14/2019 11 2 Collections and Generics
23/37
23Java
Y
8/14/2019 11 2 Collections and Generics
24/37
8/14/2019 11 2 Collections and Generics
25/37
25Java
Revisit :converting Collection intoarrays
In Collection interface: From Collection into arrayObject[] toArray() T[] toArray(T[] a)
The runtime type of the returned array is that of thespecified array.
If the collection fits in the specified array, it isreturned therein. Otherwise, a new array isallocated with the runtime type of the specifiedarray and the size of this collection.
8/14/2019 11 2 Collections and Generics
26/37
26Java
Creating your owngeneric class andgeneric methods
8/14/2019 11 2 Collections and Generics
27/37
27Java
Identifying a generic classThe method signature of a class tells us if the classuses generics.Example: List methods:
boolean add( E o)E remove(int index)
Invocation: List
Formal type parameter
Actual type parameter
8/14/2019 11 2 Collections and Generics
28/37
28Java
Code snippet of List interface
public interface List extends Collection {boolean add( E o);boolean remove(Object o);}
The type parameter can be used anywhere in thecode where class is used.
The letter E ( or T) is just a convention. Any valid java identifier could be used in place of E or T.
Recommendation is to use a single character inupper case.
8/14/2019 11 2 Collections and Generics
29/37
29Java
So multiple copies of sameclass are created when we
execute the code that has the
actual parameter
Oh no! remember type erasure- theruntime system does not have anyclue that you used generics. The
compiler simply replaces all the E
with the actual type you specified inthe code and then compiles. Not even
one extra file is generated .
d f d l
8/14/2019 11 2 Collections and Generics
30/37
30Java
User defined generic class
class Rack{
int rackNo;
ArrayList items;
Rack(){ items= new ArrayList(); }
void add(T t){items.add(t);}
void display(){
for(T b:items){
System.out.println(b);}}}
Specify the symbol thatthe class will use toidentify to generic type.
Example 6
8/14/2019 11 2 Collections and Generics
31/37
31Java
class Book{
int id;
String title;
Book(int id, String title){
this.id=id;this.title=title; }
public String toString(){
return"Id:" +id+ " Title: "+title ; }
}
8/14/2019 11 2 Collections and Generics
32/37
32Java
class BookRack{
public static void main(String[] s){
Book b1= new Book(1,"Application Developmentwith WSAD");
Book b2= new Book(2,"UML Best Practices");
Rack bookRack= new Rack();
bookRack.add(b1);
bookRack.add(b2);bookRack.display();
}}
Replaces T in Rack class
8/14/2019 11 2 Collections and Generics
33/37
33Java
Defined generic methodclass Test1{
public static Rack makeRack(Et) {
Rack rack= new Rack();
rack.add(t);return rack; }
public static void main(String[] s){
Book b1= new Book(1,"ApplicationDevelopment with WSAD");Rack bookRack= makeRack(b1);}}
Tell your method to usesymbol E for generic type
8/14/2019 11 2 Collections and Generics
34/37
34Java
Restricting to certain typesclass Test2{
public static Rack makeRack(E t) {
Rack rack= new Rack();
rack.add(t);return rack;}
public static void main(String[] s){
Book b1= new Book(1,"ApplicationDevelopment with WSAD");Rack bookRack= makeRack(b1);
}}
8/14/2019 11 2 Collections and Generics
35/37
35Java
But if we try to add CD: Rack bRack= makeRack(new CD());
we get the following compilation error:
Test.java:13: makeRack(E) in Testcannot be applied to (CD)Rack bRack= makeRack(new CD());
^
Note: Compiler does Generic arrays. T[] t= new T[]; givescompiler error!
8/14/2019 11 2 Collections and Generics
36/37
36Java
Summary of valid and invalidgeneric assignments
List a= new ArrayList() ;//ok ArrayList b= new ArrayList();
//not ok
ArrayList c= new ArrayList (); ArrayList= new ArrayList ();
//not ok ArrayList
8/14/2019 11 2 Collections and Generics
37/37
37J
ArrayList a= ref holding ArrayList