The difference between “instanceof List” and 'o instanceof List<?>\"

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I don't see any difference in the following:

    Object o = new LinkedList<Long>();      System.out.println(o instanceof List);      System.out.println(o instanceof List<?>); 

Is there any practical use of instanceof List<?> when instanceof List can't be used instead and vise versa?

回答1:

No difference. The wildcard is erased at compile time.



回答2:

According to this blog the answer is 'they are exactly the same':

as javac forbids instanceof expressions whose target type is a generic type; for casts, the compiler is slightly more permissive since casts to generic type are allowed but a warning is issued (see above). Anyway, the raw type should be replaced by an unbounded wildcard, as they have similar properties w.r.t. subtyping.

Object o = new ArrayList<String>(); List<?> list_string = (List)o; //same as (List<?>)o boolean b = o instanceof List; //same as o instanceof List<?> 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!