How to create objects dynamically during runtime Java

1912 views java

I'm trying to make a program that is going to need to dynamically create ArrayLists along the lines of this:

for (int i = 0; i < arbitraryInt; i++){
    //code to make 5 new arraylists

However I can't seem to find any method that would accomplish this.

Edit: I am trying to make a columnar cipher for my APCS class. This cipher requires me to convert a string of any length into a grid. In this case each arraylist would be a column. So to be more specific my code would look somewhat like this:

String encode = "somethingsomethingyadayadayada";
int x = 0, y = 0;

for (int i = 0; (i*i) < encode.length(); i++){
    y = i;
    x = i-1;
for (int i = 0; i < x; i++){
    //make an arraylist

Is this better @Kartic? I tried to keep it non specific as to keep my post from becoming a code dump.

answered question

Well, where do you want to put them? What do you want to do with them?

what's wrong with using new ArrayList() 5 times, or in a loop? or having List<List<Integer>>?

In the final version of what I'm trying to make, the number of arraylists will vary depending certain parameters.

@Sumtinlazy what parameters? please complete your question.. "along the lines of this" is not enough

I got an answer, updated just for you babe.

1 Answer


One of the possible solution is to store lists inside list:

List<List<Integer>> listOfLists = new ArrayList<>();
for (int i = 0; i < arbitraryInt; i++){
    listOfLists.add(new ArrayList<>());
// get third list
List<Integer> third = listOfLists.get(2);

posted this

Have an answer?


Please login first before posting an answer.