【问题标题】:Returning an element from an ArrayList of collections, where each collection has a different element type从集合的 ArrayList 中返回一个元素,其中每个集合具有不同的元素类型
【发布时间】:2016-06-19 20:26:21
【问题描述】:

我有不同类型的BagWithRandomSelect 中的ArrayList。所以arrayList.get(1) 可以返回一个BagWithRandomSelect<Integer> 对象,而arrayList.get(2) 可以返回一个BagWithRandomSelect<String> 对象。是否可以编写一个方法从 BagWithRandomSelect 返回一个元素作为它自己的类型,而不是返回一个需要强制转换的 Object

我的问题在于方法testGetFromColumn()

public class BagWithRandomSelect<E> {
    ArrayList<E> bag;
    public BagWithRandomSelect() {
        this.bag = new ArrayList<>();
    }
    public void add(E element) {
        this.bag.add(element);
    }
    public E randomSelect() {
        Random rnd = new Random();
        int rndInt = this.rnd.nextInt(bag.size);
        return this.bag.get(rndInt);
    }
}

public class DatafileCreator {
    ArrayList<BagWithRandomSelect> columnList;
    public DatafileCreator() {
        this.columnList = new ArrayList<Stack>();
    }

    // skipping some methods...

    public void addNewColumn(BagWithRandomSelect bag, String s) {
        this.columnList.add(bag);
    }

    public Object testGetFromColumn(int columnNum) {
        BagWithRandomSelect<Object> bag = this.columnList.get(columnNum);
        return bag.randomSelect();
    }
}

【问题讨论】:

  • 你试过 instanceof 吗?

标签: java generics arraylist collections


【解决方案1】:

是的,这是可能的,但您必须知道预期的对象类型。但既然你在使用Object 时无论如何都必须投射,这应该不是问题。

public <T> T testGetFromColumn(int index, Class<T> clazz) {
    BagWithRandomSelect<?> bag = columnList.get(index);
    return clazz.cast(bag.randomSelect());
}

请注意,您必须在此处使用Class 对象进行此显式转换 - 由于类型擦除将return (T) item; 转换为return (Object) item;,因此正常转换不会在运行时检查转换是否有效。否则,您可能会遇到非常讨厌的错误,例如ClassCastExceptions,在失败的代码中不存在强制转换。

然后你可以使用这样的方法:

DatafileCreator creator = ...;
...
String s = creator.testGetFromColumn(5, String.class);
Integer i = creator.testGetFromColumn(3, Integer.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2016-05-27
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多