Daniel Pitts wrote:
On Sep 20, 2:43 pm, Knute Johnson <nos...@rabbitbrush.frazmtn.com>
wrote:
chucky wrote:
When testing two objects for equality (with == operator), the
references are compared. But it is not allowed to compare the objects
(references) with <, <=, >, >= operators.
Is it possible somehow to get the address of an object and then
compare it?
What I want to do is to have each instance of my class unique, so that
two objects are equal only if they are the same object. This is easy,
I can make equals method to compare references. But I would like to
use these objects in TreeSet/TreeMap and therefore implement the
compareTo method in a way that would be consistent with respect to
equals.
I can think of one workaround: the class having an additional integer
field id and creating the instances with a synchronized factory
method. But just want to know if it is possible without that extra
field.
Thanks for replies!
Tomas
Do you not have access to the docs? It has nothing to do with == or the
address of the object. You need to look at TreeMap and Comparator.
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
A Red-Black tree based NavigableMap implementation. The map is sorted
according to the natural ordering of its keys, or by a Comparator
provided at map creation time, depending on which constructor is used.
--
Knute Johnson
email s/nospam/knute/
Whether or not the OP reads the docs, you should try reading the post
before you reply.
I did. He wants to compare unique objects with their references. And
for some unknown reason he wants to order them in a TreeMap.
He has an object that he wants its equals identity to match its ==
identity. He also wants to use said object (for some bewildering
reason) in Tree based collections.
That is why I suggested (and supplied the salient part) he read the
docs. He obviously doesn't know what a TreeMap is for.
He's probably misguided in that approach, and I've tried to suggest
alternatives to him.
I think so too. And your suggestion would have been excellent had he
not had a unique set of objects. A list will do just fine.
In any case == isn't going to be the solution to whatever his problem
is. I'll even put five bucks behind that statement.
I think his real problem is in not describing the problem he is
attempting to solve but just his method for solving it. This is a
common problem that posters on this list have. I know I've been there.