Learning JDK 7 Features Part 2: Updated Generic Instance Creation

Prior to Java 7, we create the generic instance as follows:-

List<String> list = new ArrayList<String>( );

This syntex tunrs urgly in complex situations in which the length of type parameters increases. As mentioned in Effective Java (2nd Edition) chapter 2 , Joshua suggest us a way which can reduce the verbosity of generic instance creation; as follows

public class TypeInference { 
              public static void main(String[ ] args) 
                   {
                      List list = TypeInference.newInstance(); list.add("str");
                    }
               public static ArrayList newInstance( ) 
                  {
                       return new ArrayList( );
                  }
  }

Even the previous method has an limitation that u have to insert a static method for each implementaion class.

Oracle with Java 7 comes out a way which take of this redundancy with some limitations. As suggested in oracle documenation , we can create objects with empty type parameter(<>) as long as compiler can understand the defined type at compile time. This pair of backets defined informally diamond by Oracle.

Lets understand with an example prior to Java 7:-

Map <String,HashMap<String,List<String>>> map = new  HashMap<String,HashMap<String,List<String>>>( );

In Java 7 , we can substitute the parametrized constructor with empty brackets as shown:-

Map<String,HashMap<String,List<String>>> map = new HashMap( );

Everything doesnt come free. So as Java. We cannot use subtitute the empty bracktes (<>) everywhere instead of type paramters. Lets look a at the example

List list = new ArrayList( );
list.add("A"); 
// The following statement would not compile since addAll expects Collection
list.addAll(new ArrayList( )); 

Error Msg :-The method addAll(Collection<? extends String>) in the type List<String> is not applicable for the arguments (ArrayList<Object>) . FYI : syntax for addAll

boolean addAll(Collection c);

But the following line will compile:-

list.addAll(new ArrayList( ));

Comments

  1. list.addAll(new ArrayList( )); Please explain why this will not work?

    ReplyDelete

Post a Comment

Popular posts from this blog

Fix double check locking in Java 5

When to use getClass() and instanceOf in Java

Why Time gets truncated with ResutSet getDate() function.