1

I have the following lists in a class

List<XYZ> Algo1;
List<XYZ> Algo2;
List<XYZ> Algo3;

and what I want is to create an array with these lists, try to do it like this:

List<XYZ> Algos[] = {Algo1,Algo2,Algo2};

I would like to be able to initialize it like that, but I get an error, the idea is to be able to call by means of a for and not individually

for(int i=0;i<Algos.length;i++){
    Algos[i].add(new XYZ(...));
}

Something like that, some idea?

6
  • Which error ? ^^ Commented Mar 30, 2018 at 10:03
  • none in itself, just do not compile :v Commented Mar 30, 2018 at 10:04
  • Can you explain why you unaccepted? Commented Mar 31, 2018 at 15:24
  • @Sweeper porq that solution does not satiface completely the question, it must be with an array of type List <XYZ>, unless you say that this is not possible Commented Apr 3, 2018 at 2:09
  • @SamirLlorente it is impossible. Did you look at the link? It explains this very well. Commented Apr 3, 2018 at 6:18

1 Answer 1

3

You cannot create arrays of parameterised types.

See the link for why.

Anyway, an alternative to this is to create a List<List<XYZ>>:

List<List<XYZ>> algoList = Arrays.asList(algo1, algo2, algo3);

Btw, remember to properly initialise algo 1-3 before putting them in a list! Otherwise you'll be putting nulls into a list!

If you want to add/remove stuff from algoList, you need an ArrayList<List<Algo>>:

ArrayList<List<XYZ>> algoList = new ArrayList<>(Arrays.asList(algo1, algo2, algo3));
Sign up to request clarification or add additional context in comments.

3 Comments

you might also want to suggest new ArrayList<>(Arrays.asList(algo1, algo2, algo3)) if the OP wants the algoList to be mutable.
@Aominè Seeing how OP tried to create an array of lists, I assumed that OP does not intend to add/remove stuff, but good point anyway!
Instead of using another list, can not it be with an array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.