简体   繁体   中英

Java Array Inside of Object

I am trying to access an array that is part of an object.

I am getting the error "Exception in thread "main" java.lang.NullPointerException at OrderedStringList.add(OrderedStringList.java:21) at Main.main(Main.java:24)"

I have cut my program down to the bare bones, cutting out everything that might be interfering with the output.

public class Main {

public static void main(String[] args) {

    int x = 5;

    OrderedStringList myList = new OrderedStringList();

    myList.add(x);
    }
} //end class

This code references the class OrderedStringList.

public class OrderedStringList {

public int values[];

OrderedStringList(){
    int values[] = new int[5];
}

public void add(int y) {
    values[0] = y;
    System.out.print(values[0]);
}

I assume that the numbers 21 and 24 in the error are line numbers. Because I have some things commented out in my original code, the code I have posted would normally have some content in the middle of it. Line 24 in main is: myList.add(x); . Line 21 of OrderedStringList is: values[0] = y; .

I'm guessing that there is something really simple that I am missing. Anything is appreciated.

Thanks.

Here

OrderedStringList(){
    int values[] = new int[5];
}

You shadow the class member values .

Change this to:

OrderedStringList(){
    values = new int[5];
}

You've declared values twice....

public int values[];

OrderedStringList(){
    int values[] = new int[5];
}

This commonly known as shadowing.

Change the initialization of the array in the constructor to something like...

public int values[];

OrderedStringList(){
    value = new int[5];
}

Instead...

This declares the values[] array just inside the scope of the method.

OrderedStringList(){
    int values[] = new int[5];
}

If want to refer to the Class scope use

OrderedStringList(){
    values = new int[5];
}

With the line int values[] = new int[5]; , you're declaring an entirely new int[] that exists only in the constructor. Change it to values = new int[5]; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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