Using the diamond operator for constructor type inference - Java Object Oriented Design

Java examples for Object Oriented Design:Generic Class

Description

Using the diamond operator for constructor type inference

Demo Code

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {

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

    List<Map<String, List<String>>> stringList = new ArrayList<>();

    // There's More:Using <> when the type is not obvious
    List arrayList = new ArrayList<>();
    arrayList = new ArrayList<>();
    arrayList.add("First");
    arrayList.add("Second");

    arrayList = new ArrayList();
  }//from   ww  w .j av a  2s.  co  m

  // //There's More: Understanding Erasure
  private static void useRawType() {
    List<String> arrayList = new ArrayList();
    arrayList.add("First");
    arrayList.add("Second");
    System.out.println(arrayList.get(0));
  }

  private static void useExplicitType() {
    List<String> arrayList = new ArrayList<String>();
    arrayList.add("First");
    arrayList.add("Second");
    System.out.println(arrayList.get(0));
  }

  private static void useImplicitType() {
    List<String> arrayList = new ArrayList<>();
    arrayList.add("First");
    arrayList.add("Second");
    System.out.println(arrayList.get(0));
  }

}

Related Tutorials