0

I'm trying to build an ArrayList of objects in runtime inside a method with a specific name:

public void createNewArray(String arrayName){

    ArrayList <StoreItem> arrayName = new ArrayList<StoreItem>();
}

The reason I'm trying is because, I don't know how many ArrayLists I will need to create.

What I'm trying to do is to pass a string parameter to the function (createNewArray) and then use this parameter as the ArrayList name.

Can I do such thing in Java?

Dgot
  • 119
  • 3
  • 14
  • 1
    No. If you don't know how many lists you'll have, then create a list of lists (or any other more appropriate collection of lists, depending on your use-case). – JB Nizet Nov 27 '16 at 14:51
  • 1
    You're probably looking for a `Map` instead of a `List`. See [HashMap](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html). Using a `HashMap>` would allow you to store the lists "by name". – Nicklas Jensen Nov 27 '16 at 14:53

3 Answers3

0

Use a HashMap:

    public static void main (String[] args) throws java.lang.Exception
    {
        HashMap<String, ArrayList<Integer>> map = new HashMap<String, ArrayList<Integer>>();        
    }

    public static void createNewArray(String arrayName){
        // Create your array list here
        ArrayList<Integer> list = new ArrayList<Integer>();
        map.put(arrayName, list);
    }
Aditya
  • 1,172
  • 11
  • 32
0

I don't know how many ArrayLists I will need to create.

What about using an array list of array lists? Those things exist you know.

ArrayList<ArrayList<StoreItem>> myLists = new ArrayList<>();

And you can use it just like a normal array list:

myLists.add(new ArrayList<>());
myLists.get(0).add(new StoreItem());
// ...

Alternatively, if you want to access one of your lists with a string, you can try a hash map of array lists:

HashMap<String, ArrayList<StoreItem>> myLists = new HashMap<>();

And you can just use it like a normal hash map:

myLists.put("foo", new ArrayList<>());
myLists.get("foo").add(new StoreItem());
// ...
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Why not using a HashMap of ArrayList?

public class MyArrays <T> {

     protected HashMap<String, ArrayList<T>> arrays = new HashMap<>();

     public void createNewArray(String arrayName) {
         arrays.put(arrayName, new ArrayList<T>());
     }

     public ArrayList<T> getArray(String arrayName) {
         return arrays.get(arrayName);
     }

}

You can simply use it that way:

MyArrays<StoredItem> arr = new MyArrays<>();
arr.createNewArray("first");
...
ArrayList<StoredItem> first = arr.getArray("first");
SimoV8
  • 1,382
  • 1
  • 18
  • 32