Tuesday, October 24, 2017

Good Read


Interviewed at five top companies in Silicon Valley in five days, and luckily got five job offers

https://medium.com/@XiaohanZeng/i-interviewed-at-five-top-companies-in-silicon-valley-in-five-days-and-luckily-got-five-job-offers-25178cf74e0f?lipi=urn%3Ali%3Apage%3Ad_flagship3_feed%3BVbhZxjHcQeOotBcbv7c3XA%3D%3D

Thursday, October 19, 2017

Core Java BrushUp : Generics

Always keep two things in mind
  1. Compile Type Safety
    • ArrayList stockList = new ArrayList();
    •  stockList.add(“coins”); //compiler error , String not allowed
  2. Achieved by Type Erasure
What is 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
Using old and new together
 

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);
 }