Christophe Vanfleteren wrote:
> ravi mannan wrote:
>
>> when I execute AccountManager, it's supposed to return an object
>> in the hashmap that corresponds to the key "1", which is the object
>> w/ the name "Moe Howard", instead it always returns the last object
>> put into the HashMap.
>> this is the output:
>> cp.getName:Larry Fine
>> cp.getPin:33
>> cp.getAcctNum:3
>> cp.getMaidenName:M
>>
>> after a long time debugging, I finally got rid of the "static" for the
>> data members
>> in the CustomerProfile class, and got the correct output.
>> cp.getName:Moe Howard
>> cp.getPin:11
>> cp.getAcctNum:1
>> cp.getMaidenName:F
>
> <snip code>
>
> Uou need to override the equals(Object o) and hashcode() methods if you're
> using your object in a Map.
>
> Read chapter 3 of Effective Java, it is explained in there.
> You can find a PDF copy at
> http://developer.java.sun.com/develo...effectivejava/
>
Errr, I hadn't read your problem carefully.
First of all, you only have to implement those methods if you're using your
objects a a key in a Map.
But your problem is misunderstanding of the static keyword.
When you make a field static, that same field is shared with all instances of
that class. That's why static fields are also called Class fields, because
they are shared with all instances of the class.
When you have a class like yours with all static members, you appear to have
only 1 real (different) object, because all instances share the exact smae
fields.
example:
public class AllStatic {
private static int x = 1;
//get & set method
}
now if you do
AllStatic a = new Allstatic();
Allstatic b = new Allstatic();
a.setX(11);
//b.getX() will also return 11, even if you haven't changed it in b.
If you don't make x static, each instance will have its own value for x
So the same code would result in:
AllStatic a = new Allstatic();
Allstatic b = new Allstatic();
a.setX(11);
//b.getX() will still return 1, as it has its own value for x.
--
Regards,
Christophe Vanfleteren