Reputation: 11
I'm trying to double an array in a non-static context in the following way:
public class Test {
int[] data=new int[1];
public void Double(){
if(data == null){
int[] data=new int[1];
}
int[] data=new int[data.length*2];
}
public static void main(String[] args){
Test table = new Test();
table.data=new int[1];
}
}
The javac won't compile it because it warns me that
variable data might not have been initialized
Even though it obviously has been initialized, how can I get around this?
Upvotes: 0
Views: 39
Reputation: 310893
Your code is completely pointless. data
cannot possibly be null at the point you are testing it, and the following line where you are declaring and intializing a local variable that falls out of scope immediately is equally pointless, so all the related code can be just deleted.
Upvotes: 0
Reputation: 393811
You are declaring a local data
variable in your Double()
method (actually you are declaring two such variables), which hides the instance variable having the same name.
Therefore, in the statement :
int[] data=new int[data.length*2];
You are accessing data.length
before the local data
variable is initialized.
Change it to :
public void Double(){
if(data == null){
data=new int[1];
} else {
data=new int[data.length*2];
}
}
Upvotes: 2