Val
Val

Reputation: 4366

amazing bug in code

Helo. I have two arraylist's:

public static ArrayList<Shop> shops;

with field: public static double dist;

and the second arraylist: public static ArrayList<Double> for_sort_shops;

I also have a code:

for (int i = 0; i < shops.size(); i++) {
    Log.i("palval", "for_sort_shops.get(i) = "
            + for_sort_shops.get(i));
}

for (int i = 0; i < shops.size(); i++) {
    shops.get(i).dist = for_sort_shops.get(i);
}

Log.i("palval", "---------------------------------------");
for (int i = 0; i < shops.size(); i++) {
    Log.i("palval", "shops.get(i).dist = "
            + shops.get(i).dist);
}

And what result I've get?

enter image description here

How it's possible?! Help me to understand.

Upvotes: 0

Views: 211

Answers (3)

Jochen
Jochen

Reputation: 2295

You declared dist static, which means that it's value is defined at class level and shared among all instances. in your program you only see the last value assigned to it.

Upvotes: 10

corsiKa
corsiKa

Reputation: 82559

Your field is

public static double dist

Because it's static, there's only one dist value for the entire Shops class.

You need to make this value non-static for each Shop to have it's own dist value.

Upvotes: 3

nook
nook

Reputation: 2396

Since your field public static double dist; is static, there is only one of those throughout the execution of your code. So you are updating the same variable over and over again. Take off the static off of dist to achieve your desired results.

Upvotes: 2

Related Questions