Java 从集合的ArrayList返回元素,其中每个集合具有不同的元素类型

Java 从集合的ArrayList返回元素,其中每个集合具有不同的元素类型,java,generics,arraylist,collections,Java,Generics,Arraylist,Collections,我有一个不同类型的BagWithRandomSelect的ArrayList。因此arrayList.get(1)可以返回BagWithRandomSelect对象,而arrayList.get(2)可以返回BagWithRandomSelect对象。是否可以编写一个方法,将BagWithRandomSelect中的元素作为其自身类型返回,而不是返回需要强制转换的对象 我的问题在于方法testGetFromColumn(): 公共类BagWithRandomSelect{ ArrayList袋;

我有一个不同类型的
BagWithRandomSelect
ArrayList
。因此
arrayList.get(1)
可以返回
BagWithRandomSelect
对象,而
arrayList.get(2)
可以返回
BagWithRandomSelect
对象。是否可以编写一个方法,将
BagWithRandomSelect
中的元素作为其自身类型返回,而不是返回需要强制转换的
对象

我的问题在于方法
testGetFromColumn()

公共类BagWithRandomSelect{
ArrayList袋;
公共BagWithRandomSelect(){
this.bag=新的ArrayList();
}
公共无效添加(E元素){
此.bag.add(元素);
}
公共随机选择(){
随机rnd=新随机();
int rndInt=此.rnd.nextInt(行李大小);
归还这个。袋子。获取(rndInt);
}
}
公共类DatafileCreator{
ArrayList列列表;
公共数据文件创建者(){
this.columnList=new ArrayList();
}
//跳过某些方法。。。
public void addNewColumn(BagWithRandomSelect包,字符串s){
此.列列表.添加(包);
}
公共对象testGetFromColumn(int columnNum){
BagWithRandomSelectBag=this.columnList.get(columnNum);
返回包。随机选择();
}
}

是的,这是可能的,但您必须知道预期的对象类型。但是,由于在使用
对象时必须强制转换,所以这应该不是问题

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

你试过instanceof吗?
public <T> T testGetFromColumn(int index, Class<T> clazz) {
    BagWithRandomSelect<?> bag = columnList.get(index);
    return clazz.cast(bag.randomSelect());
}
DatafileCreator creator = ...;
...
String s = creator.testGetFromColumn(5, String.class);
Integer i = creator.testGetFromColumn(3, Integer.class);