luca luca - 2 months ago 9
Java Question

Use the same method to add elements to ArrayList of String or other object

I, I would like to use the same method to add elements to

ArrayList
of
String
or
ArrayList
of other object. So the
ArrayList
is of one type but I can pass different arrayList to this method
The problem is the add method, how can I use this method to add
String
or FleetInfo (my object)?
If I use ArrayList treeFolders I have no error in this method but I can't pass 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));
}
}
}
}

Answer

As generic is compile time decision , compile will not know what kind of object you are going to insert in list , so its just through error as a part of type safety when you add object other then T

Solution 1: I think generic type T has not much required in your case you can do it with nongeneric arraylist as method parameter .

Solution 2 : you need to cast your object to T as below, but in this case you have to make sure your are passing correct class object which is synch with your Boolean parameter.

private  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){
                T t =(T)fleetPath;
                treeFolders.add(fleetPath);
                for(String statisticalFile : statisticalFolder.list()){
                    treeFolders.add(fleetPath + File.separator + statisticalFile);
                }
            }else{
              FleetInfo fleetInfo=  new FleetInfo("dir:" + fleetPath, null, null, null);
                T tfleetInfo =(T)fleetInfo;
                treeFolders.add(tfleetInfo );
                for(String statisticalFile : statisticalFolder.list()){
                    treeFolders.add(new FleetInfo("file:" + fleetPath + File.separator + statisticalFile, null, FleetType.file, null));
                }
            }
        }
    }