• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

(Java) Indexing/Keying by an Array

cleverhandle

Diamond Member
I'm trying to create a Collection that will let me keep track of objects based on their location in an xy coordinate plane. I had originally thought to do this using a HashMap keyed with an int[2] array, but that doesn't work - I'm searching the Map based on the location of a different object moving through the plane, and I can't see any way to search based on the values of the array rather than an object reference. Basically, I want to be able to ask the Collection: "Have I seen an object at this location before?" At this point, the only thing I can think of is to make the location array a member variable of the class, use an ArrayList, and iterate through the whole ArrayList checking every value against the current location. But that's obviously a very ugly solution.

Context: I'm working on a program to get a (simulated) robot to escape from a maze. At this point I have a program that works, but only for mazes without loops. I'm trying to make the program loop-tolerant by keeping track of intersections based on their location relative to my starting point.
 
Got it... used the string representation "x,y" instead of an int[]. Since all Strings with the same character representation are treated as a single object(???), that works as a key where int[] does not. Can't say I really understand the aliasing magic with Strings, but at least it works...
 
That'd work fine, or you could have wrapped the coordinates in an object who's hashCode method returns "x + (maxx * y)" (or "y + (maxy * x)")
 
Originally posted by: kamper
That'd work fine, or you could have wrapped the coordinates in an object who's hashCode method returns...
Sure. I had actually been looking at the section of the book on HashCode() when I bumped into the String stuff. Just using the String seemed much easier, if not so elegant.
"x + (maxx * y)" (or "y + (maxy * x)")
OK, sorry to be dense, but can you spell this out for me? I don't understand what this means - what's maxx * y? Is it max(x,y) or something else? I understand what you're going for, just not exactly what math you're proposing to do it.

 
maxx and maxy were just shorthand for "the highest possible value of x" and "the highest possible value of y", respectively. It's only to guarantee that you don't get hash code collisions for two different sets of co-ordinates.
 
Back
Top