Reputation: 47
I've got following class:
class Data {
double x,y,disc,asoc;
public Data(double a,double b){
x = a;
y = b;
}
}
In another class I have:
public class Kmeans {
public Kmeans(int v1,int v2){
k = v1;
samples = v2;
read();
centro();
}
Data c_data = new Data(0,0);
List<Data> data_v = new ArrayList<>();
List<Data> centroids = new ArrayList<>();
void read(){
//Reading elements from file, adding them to data_v.x and data_v.y
}
void centro(){
Random rand = new Random();
for(int i=0;i<k;i++){
int r = rand.nextInt(ilosc);
c_data.x = data_v.get(r).x;
c_data.y = data_v.get(r).y;
centroids.add(c_data);
}
for(int j=0;j<centroids.size();j++) //print centroids.x and centroids.y
}
And my main:
public static void main(String[] args) {
new Kmeans(10,10000);
}
I have a problem with centro function, when I'm trying to add randomized data from data_v.x and data_v.y to ArrayList centroids, it leads to overwriting the data in centroids. For example:
First iteration: c_data.x = -1.4067 c_data.y = 0.3626 after add: 0 index: centroids.x = -1.4067 centroids.y = 0.3626
Second iteration: c_data.x = 0.1319 c_data.y = 0.7321 after add: 0 index centroids.x = 0.1319 centroids.y = 0.7321 1 index centroids.x = 0.1319 centroids.y = 0.7321
Third iteration: c_data.x = 1.4271 c_data.y = -0.2076 after add: 0 index centroids.x = 1.4271 centroids.y = -0.2076 1 index centroids.x = 1.4271 centroids.y = -0.2076 2 index centroids.x = 1.4271 centroids.y = -0.2076
Output: Ten same elements from last iteration..
Can somebody tell me what I'm doing wrong? The data above is from debugger so the problem is with centroids.add(c_data). Randomize is fine, getting elements from file too.
Thanks
Upvotes: 1
Views: 697
Reputation: 759
The scope of reference of the c_data
object spans across all iterations of the loop, and hence the same object is getting updated in each iteration. You need to instantiate a new object in each iteration so that a new object gets added in your final list centroids
.
Upvotes: 0
Reputation: 13947
You need to do new Data()
for each object that you add to the centroids,
otherwise all the objects in the list point to the same memory slot in the heap,
and ANY
change you make to that object will be reflected on all the objects
void centro(){
Random rand = new Random();
for(int i=0;i<k;i++){
int r = rand.nextInt(ilosc);
Data c_data = new Data(0,0); //<== add this line
c_data.x = data_v.get(r).x;
c_data.y = data_v.get(r).y;
centroids.add(c_data);
}
for(int j=0;j<centroids.size();j++) //print centroids.x and centroids.y
}
on a side note in these two lines
List<Data> data_v = new ArrayList<>();
List<Data> centroids = new ArrayList<>();
define them as
List<Data> data_v = new ArrayList<Data>();
List<Data> centroids = new ArrayList<Data>();
Upvotes: 1