java 如何创建 List<Integer> 类型的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10075733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:30:10  来源:igfitidea点击:

How to create an Object of List<Integer> type

javagenericsstatic

提问by Ian Brandon Anderson

I am having trouble creating and using objects to type List<Integer>. When I run the following code, I get a NullPointerExceptionbecause the Object isn't initialized.

我在创建和使用对象键入时遇到问题List<Integer>。当我运行以下代码时,我得到一个NullPointerException因为对象未初始化

import java.util.List;

public class RBTree {

    public static class Tree {
        public List<Integer> parent;
        public List<Integer> right;
        public List<Integer> left;
        public List<Integer> data;
        public List<Boolean> black;
    }

    public static void main (String[] args){
        Tree rb =new Tree();                
        rb.data.add(-1);
        rb.left.add(-1);
        rb.right.add(-1);
        rb.parent.add(-1);
        rb.black.add(Boolean.TRUE);
    }
}

The compiler also gives me errors unless I add staticto the public static class Treeline, but I don't want Treeto be statici.e. immutable. I need to be able to use a Tree more-or-less like a structin C.

除非我添加staticpublic static class Tree行中,否则编译器也会给我错误,但我不想Tree成为static不可变的。我需要能够或多或少地像structC 中的a 一样使用 Tree 。

回答by Oliver Charlesworth

So far, you've only created a reference, there's no underlying object. Try the following:

到目前为止,您只创建了一个引用,没有底层对象。请尝试以下操作:

public List<Integer> parent = new ArrayList<Integer>();
// etc.

回答by dasblinkenlight

staticin public static classnested type declaration means that Treeobjects can be created outside the context of the RBTreeinstance. Your errors have nothing to do with static: you get NPEs because your lists are not initialized. You can add initialization in the constructor of the Tree, or add an initializer.

staticinpublic static class嵌套类型声明意味着Tree可以在RBTree实例的上下文之外创建对象。您的错误与static以下内容无关:您得到 NPE,因为您的列表未初始化。您可以在 的构造函数中添加初始化Tree,或添加初始化程序

回答by Adi

you forgot to create the actual list objects:

你忘了创建实际的列表对象:

public List<Integer> parent = new ArrayList<Integer>();
public List<Integer> right = new ArrayList<Integer>();
public List<Integer> left = new ArrayList<Integer>();
public List<Integer> data = new ArrayList<Integer>();
public List<Boolean> black = new ArrayList<Boolean>();

if you don't do this, then your lists are null and access a property or method on someting which is not there produces a NullPointerException.

如果您不这样做,那么您的列表将为空,并且访问某个不存在的属性或方法会产生 NullPointerException。