简体   繁体   English

数组列表 <DisplayMode> Java中的空指针异常

[英]ArrayList<DisplayMode> null pointer exception in Java

Inside of this class I have 在这堂课里

public DisplayMode resolutions[] = {
    new DisplayMode(1920, 1080, 32, 0),
    new DisplayMode(1680, 1050, 32, 0),
};

public ArrayList<DisplayMode> list;

and the constructor 和构造函数

14 - public myClass(){
15 -     list.add(resolutions[0]);
16 - }

I'm getting a null pointer exception on line 15. What's wrong? 第15行出现空指针异常。怎么了?

You can't add elements to your list without instantiating it (it's null ) 您不能在不实例化list情况下将其添加到list (它为null

public ArrayList<DisplayMode> list = new ArrayList<>();

I suggest you use the List interface. 我建议您使用List界面。 Also, Java naming convention would be MyClass and you could initialize list in the constructor with Arrays.asList(T...) (which I suggest you not make public ) like 另外,Java命名约定将为MyClass ,您可以使用Arrays.asList(T...) (建议您不要public )在构造函数中初始化list ,例如

private List<DisplayMode> list;
public MyClass() {
  list = new ArrayList<>(Arrays.asList(resolutions));
}

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

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