Compare Objects

Hi,

Following Situation:

I want to read data from a file, and then pass it ti my own data structure:

class Player{

String name;

Vector attributes;

}

class Attribute{

String attr_name;

int attr_value;

}

A Player has one name, but several attributes. When finish reading from the file, I put all the players in a vector.

Now my question:

I want to read then from another file. In this file we have the same players (not necessarily, there can also be more ore less players in that file). I want to compare the data of a player from the first file with the data of the same player from the second file.

Is there any 'nice' way to do that? Use a Design Pattern, maybe? Also I don't know if make sense to put all the data in a vector, would another data structure may be more appropriate (eg. for sorting the outcome later on)

Hope you understand what I wanted to explain...

Thanks

Gino

[993 byte] By [gino02a] at [2007-9-28 5:10:47]
# 1

First of all I would store all the Player objects read from file 1 into a HashMap using the Player's name as the key:

HashMap players = new HashMap ();

Player player;

while ( ( player = readNextPlayerFromFile1 () ) != null )

players.put ( player.getName (), player );

this makes it pretty easy to find it according to its name:

Player player2, player;

while ( ( player2 = readNextPlayerFromFile2 () ) != null ) {

player = players.get ( player2.getName () );

// now start comparing both objects.

}

Instead of using a separate Attribute class to store the attribute values in, it is also possible to use another HashMap inside of the Player to create this association. You only would have to use instances of class Integer to hold the int values instead or you may still keep the Attribute class and use the same mechanism as seen above:

class Player {

String name;

HashMap attributes;

public add ( Attribute attr ) {

if ( attributes == null )

attributes = new HashMap ();

attributes.put ( attr.getName (), attr );

}

}

Assuming you would like to test both instances for equality, there are certain conditions you may observe:

1) Both instances are not equal, if their names are different.

2) Both instances are not equal, if the attributes HashMap has differing numbers of key/value pairs (HashMap.size () ).

Plaese note, that if you would like to override the equals () method as specified in Object you should override the hashCode () method as well!

Woelfchena at 2007-7-9 16:21:51 > top of Java-index,Other Topics,Patterns & OO Design...
# 2
Thanks for your answer! I think I will go with your solution, using the HashMap seems to be more accurate in this situation. I may will come up with more questions ;-)ThanksGino
gino02a at 2007-7-9 16:21:51 > top of Java-index,Other Topics,Patterns & OO Design...