Java:如何创建特定父类型的集合而不是其子类型?
I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious.
我正在学习Java测试(明天),我想知道一个可能永远不会出现的问题,但让我感到好奇。
Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?
是否可以创建一个新的集合类,例如列表或只能包含特定类型而不包含其子类型的东西?我会使用泛型来实现这个目标吗?
4 个解决方案
#1
3
Not really, or at least not practically.
不是真的,或者至少不是实际的。
Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A.
子类型应该像数学集理论中的集合一样运行。如果B是A的子集,则B中的任何项目也是A中的项目。
In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B.
同样,如果B是A的子类型,则B中的任何项目也是A的项目。因此,A的任何集合必须能够维护B的项目。
That being said, there may be convulted ways that B can override certain operations to explicitly break the ability to use it in a collection or to instantiate it.
话虽如此,可能会有令人沮丧的方式,B可以覆盖某些操作,以明确地破坏在集合中使用它或实例化它的能力。
I don't think generics will solve that problem.
我认为仿制药不能解决这个问题。
更多相关文章
- 线程“main”中的异常java.lang.RuntimeException:无法编译的源代
- mvn依赖的jar,在项目中无法引用,求大神指点啊
- mybatis项目报java.sql.SQLException: Numeric Overflow的异常
- Java的Web项目中Web.xml配置文件元素详解
- 了解数组类型和使用java.util.Arrays类
- Tinking in java枚举类型的自动贩售机
- R.java was modified manually! Reverting to generated version
- 【读书笔记】JavaScript权威指南 第6版 (三)类型、值和变量
- RabbitMQ四种Exchange类型之Headers(Java)