List<String>的原生態類型就是List,即擦除了泛型信息。java
使用泛型,能夠不在編譯時期發現類型不匹配錯誤。數據庫
List<String>是List的的一個子類型,但不是List<Object>的子類型。數組
即便用泛型,但不肯定或者不關心實際的類型參數安全
例如Set<E>的無限制通配符類型爲Set<?>,即由E類型的Set變爲某個類型的Set。它與Set的區別在於通配符類型是安全的,原生態類型是不安全的。你能夠將任何類型放入到原生態Collection中,可是沒法將任何元素(除null以外)放到Collection<?>中,由於編譯器沒法識別是哪一種類型的對象。app
若是沒法消除警告,同時能夠證實引發警告的代碼是類型安全的,能夠用@SuppressWarnings("unchecked")註解來禁止這條警告。ui
若是本身沒有證實是類型安全的,仍然加這個註解,編譯時沒有警告,可是運行時若是類型不對,拋出ClassCastExceptionspa
Object[] objArr = new Long[1]; objArr[0] = "hello"; //throw ArraysStoreException
上面代碼是合法的,可是運行時會拋異常;而下面這段代碼則編譯不經過。code
List<Object> o1 = new ArrayList<Long>(); o1.add("hello");
數組是具體化的,於是在運行時才知道並檢查其元素的類型約束。對象
泛型是類型擦除的,只能在編譯時強化它們的類型信息,並在運行時擦除它們的元素類型信息,於是只能在編譯階段檢查。ci
於是數組和泛型不能很好混合使用,好比List<E>[],new List<String>[],new E[]都是非法的。
總結:數組提供了運行時的類型安全,泛型則提供了編譯時的類型安全。
public class Stack<E> { private E[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16; // The elements array will contain only E instances from push(E). // This is sufficient to ensure type safety, but the runtime // type of the array won't be E[]; it will always be Object[]! @SuppressWarnings("unchecked") public Stack() { elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(E e) { ensureCapacity(); elements[size++] = e; } public E pop() { if (size==0) throw new EmptyStackException(); E result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; } public boolean isEmpty() { return size == 0; } private void ensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } // Little program to exercise our generic Stack public static void main(String[] args) { Stack<String> stack = new Stack<String>(); for (String arg : args) stack.push(arg); while (!stack.isEmpty()) System.out.println(stack.pop().toUpperCase()); } }
方案二
public class Stack<E> { private Object[] elements; private int size = 0; private static final int DEFAULT_INITIAL_CAPACITY = 16; public Stack() { elements = new Object[DEFAULT_INITIAL_CAPACITY]; } public void push(E e) { ensureCapacity(); elements[size++] = e; } // Appropriate suppression of unchecked warning public E pop() { if (size==0) throw new EmptyStackException(); // push requires elements to be of type E, so cast is correct @SuppressWarnings("unchecked") E result = (E) elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; } public boolean isEmpty() { return size == 0; } private void ensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } // Little program to exercise our generic Stack public static void main(String[] args) { Stack<String> stack = new Stack<String>(); for (String arg : args) stack.push(arg); while (!stack.isEmpty()) System.out.println(stack.pop().toUpperCase()); } }
public static <K,V> HashMap<K,V> newHashMap(){ return new HashMap<K,V>(); }
public interface UnaryFunction<T>{ T apply(T arg); }
// Wildcard type for parameter that serves as an E producer public void pushAll(Iterable<? extends E> src) { for (E e : src) push(e); }
Set<Number> numbers = Union.<Number>union(integers, doubles);
public class Favorites { // Typesafe heterogeneous container pattern - implementation private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>(); public <T> void putFavorite(Class<T> type, T instance) { if (type == null) throw new NullPointerException("Type is null"); favorites.put(type, instance); } public <T> T getFavorite(Class<T> type) { return type.cast(favorites.get(type)); } // Typesafe heterogeneous container pattern - client public static void main(String[] args) { Favorites f = new Favorites(); f.putFavorite(String.class, "Java"); f.putFavorite(Integer.class, 0xcafebabe); f.putFavorite(Class.class, Favorites.class); String favoriteString = f.getFavorite(String.class); int favoriteInteger = f.getFavorite(Integer.class); Class<?> favoriteClass = f.getFavorite(Class.class); System.out.printf("%s %x %s%n", favoriteString, favoriteInteger, favoriteClass.getName()); } }
利用Class的cast方法,將對象引用動態地轉換爲Class對象所表示的類型。這種方法的侷限在於不能用於不可具體化的類型當中,好比List<String>,由於List<String>.class是語法錯誤。
能夠用DatabaseRaw類型表示一個數據庫行,用泛型Column<T>做爲它的鍵。