Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: edit #2

...

Code Block
bgColor#FFCCCC
public class MixedTypes {
  @SuppressWarnings("unchecked")
  private static void addToList(List list, Object obj) {
    list.add(obj);     // "unchecked" warning
  }
  private static void print() {
    List<String> list = new ArrayList<String> ();
    addToList(list, 1);
    System.out.println(list.get(0));
  }
  privatepublic static void main(String[] args) {
    MixedTypes.print();
  }
}

...

Code Block
bgColor#ccccff
class Parameterized {
  private static void addToList(List<String> list, String str) {
    list.add(str);     // "unchecked" warning
  }
  private static void print() {
    List<String> list = new ArrayList<String> ();
    addToList(list, "1");
    System.out.println(list.get(0));
  }
  privatepublic static void main(String[] args) {
	  Parameterized.print();
  }
}

...

This code suffers from related pitfalls. It compiles and runs cleanly. The method printOne is intended to print the value one either as an int or as a double depending on the type of the variable type. However, despite list being correctly parameterized, this method will always print '1' and never '1.0' because the int value 1 is always added to list without being type checked.

Code Block
bgColor#FFCCCC

import java.util.*;

public class BadListAdder {
  @SuppressWarnings("unchecked")
  publicprivate static void addToList(List list, Object obj) {
    list.add(obj);     // "unchecked" warning
  }
  publicprivate static <T> void printOne(T type) {
    if (!(type instanceof Integer || type instanceof Double))
      System.out.println("Cannot print in the supplied type");
    List<T> list = new ArrayList<T> ();
    addToList(list, 1);
    System.out.println(list.get(0));
  }
  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d); 
    BadListAdder.printOne(d);
    System.out.println(i);
    BadListAdder.printOne(i);
  }
}

...

Code Block
bgColor#ccccff
class GoodListAdder {
  publicprivate static void addToList(List<Integer> list, Integer i) {
    list.add(i);
  }
  publicprivate static void addToList(List<Double> list, Double d) {
    list.add(d);
  }
  publicprivate static <T> void printOne(T type) {
    if (type instanceof Integer) {
      List<Integer> list = new ArrayList<Integer> ();
      addToList(list, 1);
      System.out.println(list.get(0));
    }
    else if (type instanceof Double) {
      List<Double> list = new ArrayList<Double> ();

      // This will not compile if addToList(list, 1) is used
      addToList(list, 1.0);

      System.out.println(list.get(0));
    }
    else {
      System.out.println("Cannot print in the supplied type");
    }
  }
  public static void main(String[] args) {
    double d = 1;
    int i = 1;
    System.out.println(d);
    GoodListAdder.printOne(d);
    System.out.println(i);
    GoodListAdder.printOne(i);
  }
}

...