1

I am a beginner in Java and I was working on ArrayList. On a project I have a list of students . I want to create an Array list for each of these students. It's easy when you know exactly the number of students. But in that case we are not able to know the number exactly.

I have made a loop that is taking one by one all the parameters of each students. I was wondering if maybe we could create an arrayList "automatically" by just changing the name of it ? Like : (ive called x a list of word for exemple).

for(int i =o;i<x.length;i++){
   ArrayList<Matiere>x[i]  = new ArrayList<>();
}

The loop will be executed the number of times there are students and it will create an arraylist for each without me implementing them one by one. But it's not working. Do you have any ideas ?

Thanks !

  • 1
    Does this answer your question? [Assigning variables with dynamic names in Java](https://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java) – OH GOD SPIDERS Nov 03 '20 at 11:47
  • 2
    In short: What you are trying to do is not possible and smells like bad design. You shouldn't have x number of arraylist variables in your code caled "arrayList1", "arrayList2" etc. pp. Instead your data structure should try to model what you representing more accurately: There should be a `Student` class that encapsulates all data that belongs to a student and defines its relationships. So if every Student should have an `ArrayList` as an attribute then that `ArrayList` should be defined as a (non-static) field in the student class. – OH GOD SPIDERS Nov 03 '20 at 11:52
  • @OHGODSPIDERS I understand what you are saying. I have made a class to save the differents students in a text file in order to re use them the next time. But I also need to instantiate the student in the text file each time i launcg the programm. Each students has differents parameters such as nam, surname, an arraylist of all their marks (it's an arraylist of another object "topics"). So when i read my text file I wanted to create an arralist for each students to store their marks". – Laurent Louis Nov 03 '20 at 11:59
  • Please look at the first link provided. The accepted answer does what you are looking for. Bonne chance. – rajah9 Nov 03 '20 at 12:24

1 Answers1

1

If you want create an ArrayList for each students.

    Map<String, List<String>> map = new HashMap<>();

    for (int i = 0; i < count; i++) {
        map.put("name" + i, new ArrayList<>());
    }