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.

我认为仿制药不能解决这个问题。

更多相关文章

  1. 线程“main”中的异常java.lang.RuntimeException:无法编译的源代
  2. mvn依赖的jar,在项目中无法引用,求大神指点啊
  3. mybatis项目报java.sql.SQLException: Numeric Overflow的异常
  4. Java的Web项目中Web.xml配置文件元素详解
  5. 了解数组类型和使用java.util.Arrays类
  6. Tinking in java枚举类型的自动贩售机
  7. R.java was modified manually! Reverting to generated version
  8. 【读书笔记】JavaScript权威指南 第6版 (三)类型、值和变量
  9. RabbitMQ四种Exchange类型之Headers(Java)

随机推荐

  1. PHP fsockopen函数详解
  2. 用register_shutdown_function函数记录ph
  3. 关于PHP+jQuery-ui拖动浮动层排序并保存
  4. 开启PHP服务的方法
  5. 2021年最新的PHP面试题(附答案)
  6. PHP实现统计在线人数的方法
  7. php垃圾回收机制实例介绍
  8. 总结PHP编程20大效率要点
  9. PHP代码加密的几种方法介绍
  10. PHP 加密:Password Hashing API