foreach for ArrayList - unexpected behavior...

  • Thread starter Thread starter Kail
  • Start date Start date
K

Kail

Hello all,
today i found a very strange situation of ArrayList - at least for me.

let's take 3 elementes that were put into list variable (list.add(point 1 -
3)):
Point(1,1);
Point(2,2);
Point(2,2);

list is an instance of ArrayList

foreach(Point p in list) {
Point p = (Point) list[list.indexOf(p)];
Console.Writeln( p.ToString());
}

in above example we will get only elements from 0 - 1
element (2) will be never printed cause list[list.indexOf(p)];
uses a hashcode (???) to find specified elements.

i have excpected searching no by hashcode but by reference (pointer to p).


it sounds very interesting... of course one can said that this is a lame or
invalid way of thinking...
but i had expected something else...

Adam
 
Kail said:
Hello all,
today i found a very strange situation of ArrayList - at least for me.

let's take 3 elementes that were put into list variable (list.add(point 1 -
3)):
Point(1,1);
Point(2,2);
Point(2,2);

list is an instance of ArrayList

foreach(Point p in list) {
Point p = (Point) list[list.indexOf(p)];
Console.Writeln( p.ToString());
}

This code won't even compile. Aside from the misspelled method name (it's WriteLine) and the incorrect casing (it's IndexOf), you defined p twice.

After changing the loop to

Point point = (Point)list[list.IndexOf(p)];
Console.WriteLine(point.ToString());

the output is:

{X=1,Y=1}
{X=2,Y=2}
{X=2,Y=2}


Seeing that every value it accounted for, I guess either I don't understand your original problem or it was imagined in the first place.
 
Hi Adam,

May I ask why you do it this way? After all, the foreach loop will give you each Point in turn. No need to use the point to obtain it again. (Btw, the hashcode for all the points is 0)
 
Kail said:
Hello all,
today i found a very strange situation of ArrayList - at least for me.

let's take 3 elementes that were put into list variable (list.add(point 1 -
3)):
Point(1,1);
Point(2,2);
Point(2,2);

list is an instance of ArrayList

foreach(Point p in list) {
Point p = (Point) list[list.indexOf(p)];
Console.Writeln( p.ToString());
}

in above example we will get only elements from 0 - 1
element (2) will be never printed cause list[list.indexOf(p)];
uses a hashcode (???) to find specified elements.

i have excpected searching no by hashcode but by reference (pointer to p).

ArrayList.IndexOf() calls Object.Equals() to perform its comparison,
hashcode is not used. Point is a value type, not a class, so bitwise
equality is used instead of reference equality. When p is a Point(2,2),
list.IndexOf( p) will always return 1 for the list you've given because
that's the first element that matches - it doesn't matter where that
instance of Point(2,2) came from.

Since Point is a value type, there is no concept of a reference for
instances of that type.
 
Back
Top