John R
John R

Reputation: 3026

Java, Array of Objects

This is a trivial question, but my Java is rusty and it's got me stumped; I am getting a null-pointer exception. It may be obvious what I am trying to do based on the code below - but I will explain...

I need an array of objects and I don't want to create another file. For this trivial project, I do not want getters and setters. I have seen an example similar to below that uses a linked list based on a class that is located inside of another class. But, I am more proficient with arrays than linked lists, so I want to use arrays.

public class Ztest {

    Stuff[] st = new Stuff[2];

    public Ztest(){

    }

    class Stuff{
        public String x;
        public boolean y;
        public Stuff(){}
    }

    public static void main(String args[]){
        Ztest test = new Ztest();

        test.st[0].x = "hello";
        test.st[0].y = true;        
        test.st[1].x = "world";
        test.st[1].y = false;       

        System.out.println(test.st[0].x);
        System.out.println(test.st[0].y);
        System.out.println(test.st[1].x);
        System.out.println(test.st[1].y);       
    }
}

Upvotes: 0

Views: 637

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533520

You can try this if you want to use a list.

static class Stuff {
    public String x;
    public boolean y;

    // generated by my IDE.
    Stuff(String x, boolean y) {
        this.x = x;
        this.y = y;
    }

    // generated by my IDE.
    public String toString() {
        return "Stuff{" + "x='" + x + '\'' + ", y=" + y + '}';
    }
}

public static void main(String args[]) {
    List<Stuff> list = new ArrayList<Stuff>();

    list.add(new Stuff("hello", true));
    list.add(new Stuff("world", false));

    System.out.println(list);
}

prints

[Stuff{x='hello', y=true}, Stuff{x='world', y=false}]

Upvotes: 0

Joey
Joey

Reputation: 354526

You need to assign a value to st[0] and st[1] first:

test.st[0] = new Stuff();
test.st[1] = new Stuff();

Upvotes: 3

Thomas
Thomas

Reputation: 88707

You need test.st[0]=new Stuff(); etc. since Stuff[] st = new Stuff[2]; creates an array but the elements (references) are still null.

In terms of C/C++ this would be Stuff** st = new Stuff*[2];, i.e. the st is an array of pointers to Stuff instances, whereas the pointers still point to nothing yet.

Upvotes: 2

Jeff Foster
Jeff Foster

Reputation: 44706

Java allocates null for object values in new arrays. You'll need something like test.st[0] = new Stuff() before using it.

Upvotes: 2

Joseph Ottinger
Joseph Ottinger

Reputation: 4951

You need to put an instance of Stuff into test.st[0] and test.st[1].

Upvotes: 1

Related Questions