if(o instanceof Set){ //原始类型(Raw Type) Set set = (Set )o;//通配符类型(WildCard Type)}
下面的表格是泛型相关的术语:
下面这张图很好的介绍了无限制通配符和其他泛型符号之间的关系:
消除非受检警告
始终在尽可能小的范围内使用SuppressWarnings注解
Java源码中的ArrayList类中有个toArray方法,其中就有强转的警告:
@SuppressWarnings("unchecked") public T[] toArray(T[] a) { if (a.length < size) // Make a new array of a's runtime type, but my contents: return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
最好是将范围进一步缩小。将注解由整个方法到局部的变量声明上去。
@SuppressWarnings("unchecked") public T[] toArray(T[] a) { if (a.length < size){ @SuppressWarnings("unchecked") T[] result = (T[]) Arrays.copyOf(elementData, size, a.getClass()); return result; } System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
public class SomeClazz { public Object dosthWithObj(Object obj){ return obj; } public T dosthWithT(T t){ return t; } public static void main(String[] args) { SomeClazz someClazz = new SomeClazz (); Foo foo = new Foo(); Foo foo1 = (Foo) someClazz.dosthWithObj(foo); Foo foo2 = someClazz.dosthWithT(foo); }}
public class Stack { private E [] elements; private static final int MAX_SIZE = 16; private int size = 0; @SuppressWarnings("unchecked") public Stack(){ elements = (E[]) new Object[MAX_SIZE]; } public void push(E e){ ensureSize(); elements[size++]=e; } public E pop(){ if(size==0) throw new EmptyStackException(); E e = elements[--size]; elements[size]=null; return e; } private void ensureSize() { if(size==elements.length){ elements= Arrays.copyOf(elements,2*size+1); } } public static void main(String[] args) { Stack stack = new Stack<>(); for(int i =0;i<50;i++){ stack.push(i); } for(int i = 0;i<10;i++){ System.out.println(i+": "+stack.pop()); } }}class EmptyStackException extends RuntimeException{}