0

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!

user1920076
  • 103
  • 1
  • 1
  • 14

3 Answers3

2

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);
micha
  • 47,774
  • 16
  • 73
  • 80
2

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.

See: Arrays.asList(T... a)

Community
  • 1
  • 1
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • why new ArrayList, why not just Arrays.asList()? – eis Apr 04 '14 at 19:58
  • @eis: good question. That combination is ingrained in my memory but now I don't know why it ever was like that.. – Jeroen Vannevel Apr 04 '14 at 19:59
  • Might be due to fact that Arrays.asList() will give a fixed size list, you'd need to use new ArrayList for a mutable list. However, I think in this case read-only list should be ok. – eis Apr 04 '14 at 20:00
1

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.

ataylor
  • 64,891
  • 24
  • 161
  • 189