Reputation: 103
Chest is a different class which I want to make into an object, inside the chest class I just want to declare it with a bunch of values including an ArrayList which will be ints
How can I format this correctly? Thank you so much for any help!
It doesn't compile correctly.
Chest chest = new Chest(0,0,0, {0},false,false);
Hopefully this makes sense what I'm trying to do
this is the arrayList in the other class
import java.util.*;
public class Chest
{
public ArrayList<Integer> idList;
public boolean closed;
public boolean opened;
public Chest(int xpos, int ypos, int numContents, ArrayList<Integer> idList, boolean opened, boolean closed)
{
this.closed = true;
this.opened = false;
}
}
How I fixed it
Chest chest = new Chest(0,0,0, new ArrayList<Integer>(),false,false);
Thank you micha!
Upvotes: 0
Views: 213
Reputation: 66099
You can initialize it with:
new Chest(0, 0, 0, Arrays.asList(0), false, false)
Note that the return type is List<Integer>
rather than ArrayList<Integer>
, which is probably what you want anyway. There's probably no need to specify which specific implementation of the interface List
to use in the class declaration.
If you want to initialize it to an empty list, you can use:
new Chest(0, 0, 0, Collections.emptyList(), false, false)
Note in both cases, you get an immutable list.
Upvotes: 1
Reputation: 44448
A simple way:
chest = new Chest(0,0,0, Arrays.asList(5, 6, 7),false,false);
This will cause a problem with ArrayList<Integer> idList
in your constructor though. You should probably change that to List<Integer> idList
.
If not, you can use
new ArrayList<>(Arrays.asList(5, 6, 7))
as my original answer showed.
Upvotes: 2
Reputation: 49612
You can do this:
Chest chest = new Chest(0, 0, 0, new ArrayList<Integer>(), false, false);
If you want to to add values to the list you can use Arrays.asList()
as a shortcut:
List<Integer> list = Arrays.asList(1,2,3);
Chest chest = new Chest(0, 0, 0, list, false, false);
Upvotes: 2