简体   繁体   English

如何初始化arrayList <Integer> 在对象声明中

[英]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 Chest是我要制作成一个对象的另一个类,在Chest类中,我只想用一堆值声明它,包括一个ArrayList,它将是一个整数。

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 这是另一个类中的arrayList

 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! 谢谢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: 如果要将值添加到列表中,可以使用Arrays.asList()作为快捷方式:

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. 但是,这将导致构造函数中的ArrayList<Integer> idList出现问题。 You should probably change that to List<Integer> idList . 可能应该更改List<Integer> idList

If not, you can use 如果没有,您可以使用

new ArrayList<>(Arrays.asList(5, 6, 7)) as my original answer showed. new ArrayList<>(Arrays.asList(5, 6, 7))如我的原始答案所示。

See: Arrays.asList(T... a) 参见: 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. 请注意,返回类型是List<Integer>而不是ArrayList<Integer> ,无论如何,这可能是您想要的。 There's probably no need to specify which specific implementation of the interface List to use in the class declaration. 可能无需指定要在类声明中使用的接口List特定实现。

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. 请注意,在两种情况下,您都会得到一个不可变的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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