简体   繁体   English

Java中的子类型化还是泛型?

[英]Subtyping or Generics in Java?

This is a Java Assignment question, possibly concerning sub-typing and generics. 这是一个Java分配问题,可能涉及子类型和泛型。 I have a class that extends ArrayList called Rows 我有一个扩展ArrayList的类,称为Rows

public class Rows extends ArrayList<List<Thing>> implements List<List<Thing>>{}

I need to return it in another class which has a method that returns a List<List<Thing>> , thus I need to do this in order to get the desired return type: 我需要在另一个类中返回它,该类具有一个返回List<List<Thing>> ,因此我需要执行此操作以获得所需的返回类型:

private List<List<Thing>> list;

public List<List<Thing>> rows() {
    Rows r = (Rows) list;// But this cast does not work at runtime
    return (List<List<Thing>>) r;
}

The error Eclipse returns is java.lang.ClassCastException: java.util.ArrayList cannot be cast to package.Rows. Eclipse返回的错误是java.lang.ClassCastException: java.util.ArrayList无法转换为package.Rows。 I am quite confused as my Rows class extends ArrayList and I thought that it should be able to be cast to it. 当我的Rows类扩展ArrayList ,我感到很困惑,我认为应该可以将其强制转换为它。

Rows extends ArrayList<List<Thing>>

The above definition says that Rows is a subclass of ArrayList<List<Thing>> (which means it's a specialized version), not that Rows is the same thing as an ArrayList<List<Thing>> . 上面的定义说RowsArrayList<List<Thing>>子类 (这意味着它是一个专门的版本), 而不是 RowsArrayList<List<Thing>>

This means that a Rows is a kind of ArrayList<List<Thing>> (so upcasting works) but an ArrayList<List<Thing>> is not necessarily a Rows (so downcasting doesn't work). 这意味着RowsArrayList<List<Thing>> (因此,向上转换有效),但是ArrayList<List<Thing>>并不一定是Rows (因此,向下转换不起作用)。

If you have an object that you've created as a new ArrayList<List<Thing>> , then this is its type and you can't downcast it further. 如果您有一个已创建为new ArrayList<List<Thing>> ,则这是它的类型,您不能进一步对其进行向下转换。 If you want to be able to use it as a Rows , you simply need to create it it as a new Rows . 如果您希望能够将其用作Rows ,则只需将其创建为new Rows

(By the way, plural is unconventional for class names.) (顺便说一下,对于类名,复数是非常规的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM