0

So I would like to create multiple lists that have similar but different names.

So far I have:

for(int i=1; i<11; i++){
        String listName = String.format("listNumber%d", i);
        int[] listName;
    }

How can I change the third line so I would get listNumber1, listNumber2 etc

2
  • 1
    You want to change the variable name? Variable names cannot be changed programmatically and are there for readability. Commented Mar 3, 2016 at 15:52
  • Either make them into an array so you get listName[0], listName[1] etc. or make a list of lists. There is no way to dynamically generate a set of variable names. Commented Mar 3, 2016 at 15:54

2 Answers 2

2

In short, you can't. You could create a map containing your arrays:

Map<String, int[]> listMap = new HashMap<>();

for(int i=1; i<11; i++){
    String listName = String.format("listNumber%d", i);
    listMap.put(listName, new int[arraySize]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot use String on a variable name in Java.

If you want to use String to access a List, you can use Map;

Map<String, List<Integer>> lists = new HashMap<>();
lists.put("listNumber1", new ArrayList<Integer>());
lists.put("listNumber2", new ArrayList<Integer>());

lists.get("listNumber1").add(1);

But if you use String to itarate the lists, you can use array of List or List of List;

List<List<Integer>> lists = new ArrayList<>();
lists.add(new ArrayList<>());
lists.add(new ArrayList<>());

for(List<Integer> list : lists) {
    list.add(1);
}

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.