import java.util.ArrayList; class Apple { private static long counter; private final long id = counter++; public long id() { return id; } } class Orange { } /** * * 此处未使用泛型,当试图将orange对象转型为apple是,你就会得到一个语法错误; * @author hong.su * */ //public class AppleandOrangeWithoutGenerics { // @SuppressWarnings("unchecked") // public static void main(String[] args){ // ArrayList apple = new ArrayList(); // for (int i = 0; i < 3; i++) { // apple.add(new Apple()); // apple.add(new Orange()); // for (int j = 0; j < apple.size(); j++) { // ((Apple)apple.get(i)).id(); // } // } // } //} public class AppleandOrangeWithoutGenerics{ @SuppressWarnings("unchecked") public static void main(String[] args){ ArrayList<Apple> apples = new ArrayList<Apple>(); for (int i = 0; i < 3; i++) { apples.add(new Apple()); for (int j = 0; j < apples.size(); j++) { System.out.println(apples.get(j).id()); for (Apple c : apples) { System.out.println(c.id()); } } } } }