java使用相同的方法向字符串或其他对象的ArrayList添加元素
我,我想使用相同的方法将元素添加到String
的ArrayList
或其他对象的ArrayList
中。所以ArrayList
是一种类型,但是我可以将不同的arrayList传递给这个方法
问题是add方法,如何使用此方法添加String
或FleetInfo(我的对象)?
如果我使用ArrayList树文件夹,我在这个方法中没有错误,但是我不能传递ArrayList
private <T> void addStatisticalFiles (String fleetName, ArrayList<T> treeFolders, boolean isFleetInfo){
String fleetPath = env.getRequiredProperty(PROPERTY_NAME_FILESYSTEM_BASEPATH) + fleetName + File.separator + "statistics";
File statisticalFolder = new File(fleetPath);
if (statisticalFolder != null && statisticalFolder.exists()){
if (!isFleetInfo){
treeFolders.add(fleetPath);
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(fleetPath + File.separator + statisticalFile);
}
}else{
treeFolders.add(new FleetInfo("dir:" + fleetPath, null, null, null));
for(String statisticalFile : statisticalFolder.list()){
treeFolders.add(new FleetInfo("file:" + fleetPath + File.separator + statisticalFile, null, FleetType.file, null));
}
}
}
}
# 1 楼答案
由于泛型是编译时决策,compile将不知道要在列表中插入什么类型的对象,所以当您添加对象而不是T时,作为类型安全性的一部分,这是一个完全错误
解决方案1:我认为泛型类型T在您的案例中没有太多要求,您可以使用非泛型arraylist作为方法参数
解决方案2:您需要将对象强制转换为T,如下所示,但在这种情况下,您必须确保传递的是与布尔参数同步的正确类对象