Always keep two things in mind
Below code:
is compiled into
Also Note
Using old and new together
What’s difference between E , T or ?
- Compile Type Safety
- ArrayList
stockList = new ArrayList (); - stockList.add(“coins”); //compiler error , String not allowed
- Achieved by Type Erasure
Below code:
List<String> list = new ArrayList<String>(); list.add("Hi"); String x = list.get(0);
is compiled into
List list = new ArrayList(); list.add("Hi"); String x = (String) list.get(0);
Also Note
- it uses Autoboxing
- cannot be applied to primitive type
cannot mix old and new types as it will not guarantee type safety limit Types parameters, by using
ArrayList<String>myList2 = new ArrayList <String>(); // valid // BELOW is mixing of OLD + NEW Generics in such code there is
// no guarantee of type safety ArrayList myList3 = new ArrayList<String>(); // valid ArrayList<String>myList4 = new ArrayList(); // valid
What’s difference between E , T or ?
- type parameter (E or T).
- ? is used as a wildcard which is used when providing a type argument, e.g. List foo = ... means that foo refers to a list of some type, but we don't know what.
void point_1( ){ Set<Object> SetOfObject = new HashSet<String>(); //compiler error - incompatible type Holder<int> numbers = new Holder<int>(10); //compiler error - unexpected type required: reference found:int } void point_2( ){ List<Parent> parent_List = new ArrayList<Parent>(3); List<Child> child_List = new ArrayList<Child>(3); parent_List.add(new Parent("father 1")); parent_List.add(new Parent("father 2")); parent_List.add(new Child("child 1")); //upcasting ok child_List.add(new Child("lil 1")); child_List.add(new Child("lil 2")); child_List.add((Child)new Parent("Father of 1"));//HAVE to CAST as usual
// List<Parent> myList = new ArrayList<Child>(); // ** ERROR ** .. incompatible types ... // polymorphism applies here ONLY to List & ArrayList ... ie ... base_types .. not generic_types Parent[] myArray = new Child[3]; // but this works.. // WHY .. it works for arrays[] and not for generics .. coz compiler & JVM behave differently for generic collec & arrays[] point_8(child_List); }
No comments:
Post a Comment