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
How to create an Object of List<Integer> type
提问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 NullPointerException
because 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 static
to the public static class Tree
line, but I don't want Tree
to be static
i.e. immutable. I need to be able to use a Tree more-or-less like a struct
in C.
除非我添加static
到public static class Tree
行中,否则编译器也会给我错误,但我不想Tree
成为static
不可变的。我需要能够或多或少地像struct
C 中的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
static
in public static class
nested type declaration means that Tree
objects can be created outside the context of the RBTree
instance. 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.
static
inpublic 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。