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 !

4
  • 1
    Does this answer your question? Assigning variables with dynamic names in Java Commented Nov 3, 2020 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. Commented Nov 3, 2020 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". Commented Nov 3, 2020 at 11:59
  • Please look at the first link provided. The accepted answer does what you are looking for. Bonne chance. Commented Nov 3, 2020 at 12:24

1 Answer 1

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<>());
    }
Sign up to request clarification or add additional context in comments.

Comments

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.