Reputation: 532
I am writing a program that has a double array called data.
My code so far is the following.
public class DataSet {
private double[] data;
private int dataSize;
public DataSet(){
dataSize = 0;
data = new double [10];
}
public void add(double x){
if(dataSize>= data.length){
double[] newData = new double[data.length*2];
System.arraycopy(data, 0, newData, 0, data.length);
newData=data;
newData[dataSize]=x;
dataSize++;
}
else{
data[dataSize] = x;
dataSize++;
}
}
}
as you can see I am adding new values to the array using the add method. However what I am unsure of is that when I do
newData=data;
Can I just make this change to the next line?
data[DataSize] = x;
The reason why I am asking is whether the by setting the two arrays equal to each other, whenever I call data, I am in fact calling newData.
Upvotes: 1
Views: 10606
Reputation: 4197
You've lost your created array (stored in newData
) by assigning newData=data;
Replace
newData=data;
newData[dataSize]=x;
by
data = newData;
data[dataSize]=x;
Upvotes: 2
Reputation: 533500
You need to reassign data
. There is also some tools in the JVM which help you.
public void add(double x) {
if (dataSize >= data.length)
data = Arrays.copyOf(data, data.length * 2);
data[dataSize++] = x;
}
Upvotes: 5