Flauslord
Flauslord

Reputation: 15

Why I can't add CustomType ArrayList to ArrayList of Object ArrayLists?

I have Singleton class like this:

public class Singleton
    private static Singleton instance;
    private ArrayList<Release> releases;
    private ArrayList<Place> places;
    ArrayList<ArrayList<Object>> list = new ArrayList<ArrayList<Object>>(2);

   private Singleton() {
       releases = new ArrayList<Release>();
       places = new ArrayList<Place>();
       list.add(release); //error, required AL<Object>, provided AL<Release> 
       list.add(places); //same
   }

   public static Singleton getInstance(){
    /* Singleton code */
   }

I thought that it is possible because, every Class extends Object class. My intention is to read from files where ALs are saved as object a then these ALs have in collection of one AL, where al.get(PLACES_INDEX) would return places and so on. It is a good approach or am I missing something?

Later on I would like to have some unified method, which would be something like:

public ArrayList<T> getArrayList() {
   /*return places or releases based on <T>*/
}

I don't know if it's even possible since this class is Singleton.

Upvotes: 1

Views: 76

Answers (1)

M A
M A

Reputation: 72844

I will explain why you're getting the error, but from what you describe this looks like a bad design for your class: don't store "generic" lists in a list, to access them based on a certain index. And don't create a method like public ArrayList<T> getArrayList() { that returns one of the lists depending on the type T. This is overengineering, and makes your code much harder to maintain, and easy to break.

Just keep the distinct lists separately, and provide getters for each one of them. If you are reading from a file and want to deserialize the content into a data structure, simply create a class structure that models the content. Your code will be much simpler and easier to read.

Even though Release is a subclass of Object, ArrayList<Release> is not a subclass of ArrayList<Object>, therefore you cannot add an ArrayList<Release> to an ArrayList<ArrayList<Object>> (we say that generics are not covariant). If Java allowed you to do that, then you can end up with a scenario that breaks generic usage of the code:

ArrayList<ArrayList<Object>> list = new ArrayList<>();
ArrayList<Release> releases = new ArrayList<>();
list.add(releases);   // imagine this is allowed
ArrayList<Object> releasesFromList = list.get(0);
releasesFromList.add(place); // oops, added a place to list of release

Upvotes: 2

Related Questions