T
Thomas4321
Gast
Hallo,
ich glaube, ich habe ein Verständnisproblem mit der equals()-Methode. Nachfolgend mein Beispielcode, der nicht das tut, was ich eigentlich von ihm erwarte.
Meine Erwartung ist: ich definiere eine equals()-Methode, die behauptet, alle Objekte der Klasse MyTest seien gleich (nicht, dass das für eine Anwendung sinnvoll wäre, aber es bringt mein Problem auf den Punkt).
Ich füge das Objekt t1 in einen Vector ein und teste dann mit contains(), ob t2 im Vector enthalten ist. Da alle MyTest-Objekte in diesem Fall gleich sind, müsste t2 bereits "enthalten" sein. Ist es aber nicht. Warum?
Die Sun-Dokumentation sagt zu contains():
"true if and only if the specified object is the same as a component in this vector, as determined by the equals method; false otherwise."
% java MyTest
true
true
false
[/code]
ich glaube, ich habe ein Verständnisproblem mit der equals()-Methode. Nachfolgend mein Beispielcode, der nicht das tut, was ich eigentlich von ihm erwarte.
Meine Erwartung ist: ich definiere eine equals()-Methode, die behauptet, alle Objekte der Klasse MyTest seien gleich (nicht, dass das für eine Anwendung sinnvoll wäre, aber es bringt mein Problem auf den Punkt).
Ich füge das Objekt t1 in einen Vector ein und teste dann mit contains(), ob t2 im Vector enthalten ist. Da alle MyTest-Objekte in diesem Fall gleich sind, müsste t2 bereits "enthalten" sein. Ist es aber nicht. Warum?
Die Sun-Dokumentation sagt zu contains():
"true if and only if the specified object is the same as a component in this vector, as determined by the equals method; false otherwise."
% java MyTest
true
true
false
Code:
import java.util.Vector;
class MyTest
{
public boolean equals(MyTest e)
{
return true;
}
public static void main(String args[])
{
Vector v = new Vector();
MyTest t1 = new MyTest();
MyTest t2 = new MyTest();
v.add(t1);
System.out.println(v.contains(t1));
System.out.println(t1.equals(t2));
System.out.println(v.contains(t2));
}
}
[/code]