new to java and need some pointers
I am trying to create an array list in one class then return it and iterate through its values in a separate main class. However when i use the get method to return a specific value in the array it produce a null pointer exception. What am I doing Wrong ?
import java.util.*
public class ReadFile
{
private ArrayList<Integer> height;
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x )
{
height.add(x);
}
}
public ArrayList<Integer> getHeights()
{
return height;
}
}
Main Class
import java.util.*
public class Jumper
{
private ReadFile readFile;
public Jumper()
{
readFile = new ReadFile();
}
public static void main(String[] arg)
{
Jumper game = new Jumper();
System.out.println(game.readFile.getHeights().get(1));
}
}
CodePudding user response:
You're declaring a field named height:
private ArrayList<Integer> height;
and then you're déclaring a local variable also named height:
public ReadFile()
{
ArrayList<Integer> height = new ArrayList<Integer>();
everything you do with height in the constructor is done on the local variable, and nothing is done on the field.
CodePudding user response:
This line is the problem
ArrayList<Integer> height = new ArrayList<Integer>();
Instead of assigning a value to the height member field, you create a new height variable that only exists inside the constructor.
You should instead do height = new ArrayList<Integer>();, similar to how you do with readFile.
P.S: Having a local variable with the same name as a member field is called "variable shadowing". Depending on what IDE you are using, it might warn you about it, as it's not an uncommon mistake.
CodePudding user response:
Please change this line ArrayList<Integer> height = new ArrayList<Integer>(); to height = new ArrayList<Integer>(); inside the constructor of ReadFile. What happens is both the height references are different.
In this code
public ReadFile() {
ArrayList<Integer> height = new ArrayList<Integer>();
for(int x = 0; x <= 3; x ) {
height.add(x);
}
}
The height is local to the Constructor ReadFile(), so only that is initialized and the private ArrayList<Integer> height; remains null and that's what causes the Exception.
