How create a filled ArrayList

I am trying to make a game for fun. It is about exploring rooms and fighting enemies (similar to ‘enter the gungeon’, but completely 2D, rooms require teleportation to switch and way less mechanics)

What I am trying to do is:
While creating a room (object) I pass into it the arguments I want. One of those is an ArrayList which is filled with objects. Would it be possible to fill the arraylist while it is being created?

How I imagine it would look like:

room r = new room(0, 600, 600, new ArrayList<obstacle>()[]{new obstacle(1,2,3,4)});
//taking inspiration from:
println(new obstacle[]{new obstacle(1,2,3,4)});

Is it even possible to do it?

Now that I think of it, passing an ArrayList wouldn’t be absolutely needed, since I can just pass a normal 1D array[] and add all of the items to an empty ArrayList but still.

Thank you!

1 Like

i don’t know if i follow but you mean something like

import java.util.Arrays;

class Obstacle
  int foo;
  Obstacle(int foo) { = foo;

Obstacle[] obstaclesArray = new Obstacle[]{new Obstacle((int)random(100)), new Obstacle((int)random(100))};

ArrayList<Obstacle> obstaclesArrayList = new ArrayList<Obstacle>(Arrays.asList(obstaclesArray));

for(Obstacle ob : obstaclesArrayList) {

or sticking closer to your example

import java.util.Arrays;

class Obstacle {
  int foo;
  Obstacle(int foo) { = foo;

class Room {
  int foo1;
  float foo2;
  ArrayList<Obstacle> obstacles;
  Room(int foo1, float foo2, ArrayList<Obstacle> obstacles) {
    this.foo1 = foo1;
    this.foo2 = foo2;
    this.obstacles = obstacles;

Room room1 = new Room((int)random(100), random(100), new ArrayList<>(Arrays.asList(new Obstacle[]{new Obstacle((int)random(100)), new Obstacle((int)random(100))})));


but your last idea is probably the best approach


I do like the flexibility of arralists sometimes you just don’t know the number of items you will have and whilst you could get around this buy initialising a larger array than necessary arraylists require no such additional code.

Do bear in mind that ints have to be initialised as Integer same with floats just something you have to be mindful of.

Essentially though an arraylist is either created empty or null, if its empty then you have to then fill it using add(). If it’s null you first have to initialise it ie make it empty. Of course you can create a null arraylist and set as another live array, although from recollection I may be wrong, doing so has the same limitation as setting an array to another array meaning that the arraylist will simply be a symbolic link to the original and will not in fact be a copy.

Again something to keep in mind

You can also have arraylists of arraylists arraylists of hashmaps or any other type of object that is normally handled in java.