Java中的范型类型强制转化注意2
2016-04-26 07:54
489 查看
Type mismatch Error : Cannont convert from ArrayList<SubClass1> to List<SuperClass>
It seems you're trying to create a list that only contains objects from the particular subclass. In this case you just need the generics to play nice at compile time. (Generics are erased at runtime :) )
你需要使用一个有界限的通配符在你的ArrayList声明中。
You should use a bounded wildcard in your ArrayList declaration:
这个‘?’表示一个通配符,它定义个不知道的类型,但是使用一个有界限的通配符,你可以确定它是一个未确定的类型,这个类型是
SuperClass的子类型。
The
a wildcard and defines an unknown type. But by using a bounded wildcard you can assure that it is an unknown subtype of SuperClass.
For further information about wildcards see here.
Concerning you're other problem:
The type of the parameter to list.add() is ? extends
SuperClass-- an unknown subtype of SuperClass. Since we don't know what type it is, we don't know if it is a supertype. it might or might not be such a supertype, so it isn't safe to pass a SubClass1 or SubClass2 there.
It seems you're trying to create a list that only contains objects from the particular subclass. In this case you just need the generics to play nice at compile time. (Generics are erased at runtime :) )
class AClass<T extends SuperClass> { List<T> list; public AClass(){ list = new ArrayList<T>(); } void addObjects(T obj){ list.add(obj); } }
shareimprove this answer |
You should use a bounded wildcard in your ArrayList declaration:
class AClass{ List<? extends SuperClass> list; public AClass(boolean b){ if(b) list = new ArrayList<SubClass1>(); else list = new ArrayList<SubClass2>(); } } }
这个‘?’表示一个通配符,它定义个不知道的类型,但是使用一个有界限的通配符,你可以确定它是一个未确定的类型,这个类型是
SuperClass的子类型。
The
?is
a wildcard and defines an unknown type. But by using a bounded wildcard you can assure that it is an unknown subtype of SuperClass.
For further information about wildcards see here.
Concerning you're other problem:
The type of the parameter to list.add() is ? extends
SuperClass-- an unknown subtype of SuperClass. Since we don't know what type it is, we don't know if it is a supertype. it might or might not be such a supertype, so it isn't safe to pass a SubClass1 or SubClass2 there.
相关文章推荐
- Java中的范型类型强制转化注意
- java jdk7 并行计算框架 fork/join
- Java简介
- package和import
- 闲谈
- Spring Data Jpa 查询返回自定义对象
- 多态、抽象类、接口、区别(java基础知识九)
- 我对java的理解(一)——注解就是贴标签
- Java---IO加强(2)
- Java---IO加强(2)
- 重新学javaweb---cookie&&session
- springmvc图片上传遇到的问题(除了图片还要传文字)乱码参数取不到
- 20145333《Java程序设计》第3次实验报告
- 停止Java线程,小心interrupt()方法
- 在java web项目中集成webservice
- 了解 Spring Data JPA
- JAVA多线程实现的三种方式
- JavaWeb自定义标签
- Java Basis
- java:main class not find:Unsupported major.minor version 51.0