简体   繁体   中英

How do I initialize an arrayList<Integer> within a object declaration

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!

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);

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM