0

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.

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.

4

3 回答 3

5

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

public List<Integer> parent = new ArrayList<Integer>();
// etc.
于 2012-04-09T15:44:08.210 回答
2

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.

于 2012-04-09T15:46:02.083 回答
1

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.

于 2012-04-09T15:44:54.850 回答