We are moved to new domain
Click -> www.ehowtonow.com
Tuesday, 31 December 2013

Java7 – Type Interface for Generic Instance Creation

In this tutorial we are going to see about type Interface for Generic instance creation in Java7 and previous Java versions.

Diamond syntax for more concise new expressions

Historically, you had to specify type arguments for a generic class in a new expression.

Before Java7

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

Note the above  declaration full type is specified twice.So, there is redundant in code.

In Java7  

In Java7,  you can replace the type arguments with the diamond notation, (<>), to take advantage of automatic type inference. The resulting code is functionally identical, but more concise and easier to read. For example

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

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:

Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List<String> list = new ArrayList<>();
list.add("A");

  // The following statement should fail since addAll expects
  // Collection<? extends String>

list.addAll(new ArrayList<>());

Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.

In comparison, the following example compiles:

// The following statements compile:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java7 – Type Interface for Generic Instance Creation Rating: 5 Reviewed By: eHowToNow