Implementation of Equals - ???

The spec says:
for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
Suppose, if class A is a subclass of class B,
ob1 is an object of class A and ob2 is an object of class B,
then is it necessary that
if ob1.equals(ob2) is true, then
ob2.equals(ob1) should also be true ???

Also remember to override the hashCode().
I think it would be more correct to say that ob1.equals(ob2) and ob2.equals(ob1) is false, since they are instantiated from different classes, even though class A is a subclass of class B. Usually you would just check if ob2 is an instance of A when you compare ob1 with ob2, and viceversa instance of B, in which case the first would be false and the second would be true, but that is not correct to do, since x.equals(y) should equal y.equals(x). You could override hashCode in class A so it is different from that calculated by B, because the Collection classes will first check the hashCode, then the equals method, to check whether to elements are the same.

Similar Messages

  • Implementation of equals, hashCode, and

    I am writing an RMI application where the implementation of the remote interface cannot extend UnicastRemoteObject because it already extends another class. So, I need to explicitly export the server object using UnicastRemoteObject.exportObject(server, 0);� no problem.
    Problem is I�ve read that in order to make the class behave as if it had extend UnicastRemoteObject, you must provide implementations for equals, hashCode, and toString. I�ve searched the world over for implementations of these methods equivalent to those found in UnicastRemoteObject� no luck so far.
    Could you help me out?
    I�ve found some code that I�ve listed below� Is it equivalent to the equals and hashCode method found in UnicastRemoteObject? What about toString()?
    public class RemoteDataServer extends LocalDataServer implements RemoteInterface{
        private Remote serverStub;
        public RemoteDataServer() throws IOException {
            super();
            //export remote object
            serverStub = UnicastRemoteObject.exportObject(this);
        public boolean equals(Object obj) {
            return (obj == this || serverStub.equals(obj));
        public int hashCode() {
            return serverStub.hashCode();
    //toString()???

    Hi,
    At book Effective Java by Joshua Bloch you can see some info
    overriding these members.
    See at http://java.sun.com/docs/books/effective/index.html
    Here is the toString()spec method from Object :
    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
    getClass().getName() + '@' + Integer.toHexString(hashCode())
    but toString from class String simply returns the string contents of
    an object.
    Hope this help

  • Adivce on implementing boolean equals(Object)

    Given that SomeClass extends Object and is is not part of an overly complicated hierarchy where each subclass adds some data useful to identify its instances.
    Which version is better and why?
    public boolean equals(Object o){
        return (o != null
            && this.id != null
            && this.getClass().equals(o.getClass())
            && this.id.equals(((SomeClass) o).id))
        || super.equals();
    public boolean equals(Object o){
        return (o != null
            && this.id != null
            && o instanceof SomeClass
            && this.id.equals(((SomeClass) o).id))
        || super.equals();
    }

    So your question is about instanceof vs. comparing the results of getClass, right?
    It depends on the semantics of your hierarchy.
    The contract of equals says it has to be symmetric. a.equals(b) must return the same result as b.equals(a).
    class Super {
    class Sub extends Super {
    Super super = new Super();
    Sub sub = new Sub();
    boolean b1 = super.equals(sub);
    boolean b2 = sub.equals(super); If you use instanceof, then super's equals must be final, or else Sub's equals must only check for instance of Super, not instanceof Sub. If Super checks for instanceof Super, and Sub checks for instanceof Sub, then b1 (super.equals(sub)) can be true (since sub is an instance of Super) but b2 (sub.equals(super)) can never be true.
    If you look at the collections hierarchy, you'll see that the equals methods check for instanceof the interface. For instance (HA!), two Lists are equal iff they both implement List, and they have the same elements in the same order. So ArrayList, LinkedList, and any custom List that you might implement must check instanceof List, not instanceof ArrayList, etc.
    The general rule is, if you're going to use instanceof, then to preserve symmetry, all classes in the subtree must check for instanceof the same class (or interface), and it has to be at the highest (closest to Object) level in the subtree of classes that could be equal to each other.
    Does that make sense?
    ¶

  • Method "equals" not implemented for class "Pan1"

    Method "equals" not implemented for class "Pan1" -- this is the error I'm getting while running one static Analyzer. Can anybody say, what is this error , and how to rectify it ?

    The static analyzer may have noticed that either you may invoke .equals() on instances of this class (possibly through polymorphism) and you have not implemented the method in your class. This is most likely a warning since many times lack of an implemented .equals() method in such cicumstances will lead to Object.equals() being executed and that simply checks to see if the object references are the same - quite a bit stronger than what one would probably expect from .equals();
    it is also possible that you did implement an equals() method but that you used the wrong argument type. This is a common mistake:
    public boolean equals(MyClass other) {
       return /* something */;
    }This type of warning may be ignored, or if it troubles you and there is no way to disable it for the classes that you know you have implemented correctly, you might consider adding an equals method of the form:
    public boolean equals(Object other) {
       return super.equals(other);
    }Chuck

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • Equals and lazy loading

    Hi all,
    We have an application in which we use lazy loading on our client, so we can't be sure that both objects have the same objects reference loaded already. While implementing the equals method I came to the problem if it makes sense to compare the lazy loaded objects as well, because this might lead to a very deep object comparison through the whole object tree which might be very unperformant if I load this references on demand. Otherwise not comparing the references might be an incomplete comparision of these objects and makes the usage of the equals method very difficult.
    Has anyone experience using the equals method with lazy loading?
    Thanks in advance
    Marco

    Okay - here comes a little more detail about our architecture to give you a deeper understanding. Currently we are working with EJB3 / JBoss environment but our intention is to encapsulate this through a DAO-layer. Anyways we have special object-dependencies as per example a customer has it�s orders. So in my understanding a customer with the an address, a name etc. with NO orders is not the same as a customer with the same address and the same name and let�s say 2 orders. So I can stick with comparing simply the name and the address, but this wouldn�t give you an exact comparison.
    The other way would be to compare the orders as well, but what if the orders have a number of invoices behind them. The conclusion would be, that I�d have to compare them as well. Additionally I have the problem, that I have totally equal customers with the same number of orders and invoices, but the first one has a null-value in its orders, because they have not been loaded from database yet and the other one has. So my technique with comparing the lazy-loaded references would not work here. A complete loading of all references for a comparison cannot be the solution here either.
    So it is hard to say if they are I/O intensive. Worst case would be, that we have to load the complete object-tree for comparison from database and send them between client and server (jboss). This is part of our question? Should this be the consequence of lazy loading or is it best pratice to stick with the local attributes and let the client do the work, so that he has to work through the whole object-tree if he wants to know the exact equality.
    Does this give you a more detailled view of our question? I guess I am not the first to deal with this problem, so I�d like to share your experiences with you about what is "wise" to do.
    Thanks for your help
    Marco

  • How to write hasCode() & equals(0) methods in Compound Key Class

    Hi Java Helpdesk,
    I am wondering how to write the hashCode() and equals() methods that is mandatory when creating composite
    @IdClass. Below is the combination of primary @Id keys that I would like to make up in a compound key class:
    public final class PatientKey implements java.io.Serializable
        private String firstnameId;
        private String SurnameId;
        private String DateOfBirthID;
        private String Sex;
        public int hashCode()
        public boolean equals(Object otherOb)
    }The Order application in Java EE 5 Tutorial (page 841) is made up of only 2 primary keys.
    Thanks,
    Jack

    Hi,
    Thanks for your very brief response and I had a look at both EqualsBuilder and HashCodeBuilder from the URL links you have provided. These methods may improve the comparison accuracy but I was more interested on how to implement the equals() and hashCode methods when comparing 3 or more primary keys in order to make up a primary key class. Below is my first attempt to compose the PatientPK primary key class:
    1. public class PatientPK implements java.io.Serializable {
    2.
    3.     private String firstName;
    4.     private String lastName;
    5.     private String dateOfBirth;
    6.     private Char sex;
    7.
    8.     public PatientPK() {}
    9.
    10.   public PatientPK(String firstName, String lastName, Date dateOfBirth, Char sex)
    11.   {
    12.       this.firstName = firstName;
    13.       this.lastName = lastName;
    14.       this.dateOfBirth = dateOfBirth;
    15.       this.sex = sex;
    16.   }
    17.
    18.   public String getFirstName() { return this.firstName; }
    19.   public void setFirstName(String firstname) { this.firstName = firstName; }
    20.
    21.   public String getlastName() { return this.lastName; }
    22.   public void setLastname(String lastName) { this.lastName = lastName; }
    23.
    24.   public String getDateOfBirth() { return this.dateOfBirth; }
    25.   public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; }
    26.
    27.   public Char getSex() { return this.sex; }
    28.   public void setSex(String sex) { this.sex = sex; }
    29.
    30.   public boolean equals(Object obj)
    31.   {
    32.       if (obj == this) return true;
    33.       if (!(obj instanceof PatientPK)) return false;
    34.       PatientPK pk = (PatientPK) obj;
    35.       if (!firstName.equals(pk.firstName)) return false;
    36.       if (!lastName.equals(pk.lastName)) return false;
    37.       if (!dateOfBirth.equals(pk.dateOfBirth)) return false;
    38.       if (!sex.equals(pk.sex)) return false;
    39.       return true;
    40.   }
    41.
    42.   public hashCode()
    43.   {
    44.       return firstName.hashCode() + lastName.hashCode() + dateOfBirth.hashCode() + sex.hashCode();
    45.   }
    46.}Please advice whether both these equals() and hashCode() implementations are correct.
    Thanks in advance,
    Jack

  • Collection.equals

    The javadocs for collection.equals states
    "The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both the Set and List interfaces.) "
    Why not? Couldn't a class implement both List and Set and compare either way, depending on what kind of object it is being compared with?
    FYI I grumbled about equals before in a previous post
    http://forum.java.sun.com/thread.jspa?forumID=425&threadID=619976
    I was just working on something and came across a bug in my code because I was hashing something using an arrayList as a key, and I believed incorrectly that equals would be implemented the same way it is for arrays.
    It seems weird to me that Collection, List and Set require symmetry and transitivity between all classes implementing them, but CharSequence (an interface implemented by both String and StringBuffer, ala my other post) does not.
    CharSequence states:
    "This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map"
    Ok. So the guys working on Java have given us at least three or four different patterns to follow here: There are arrays which we know are only equal if they are the same array. There's the Object (general) implementation of equals in which we can count on objects of different classes being different. There's List and Set where all lists and sets are equal to other lists and set respectively, and there's the CharSequence pattern in which all bets are off.
    Wouldn't it be easier for people to learn and program in java if they could rely on one of these patterns without having to go through the javadocs with a fine toothed comb?

    No.
    Let's say you have a List, (L) a Set (S) and a
    List/Set (LS).
    You want both of the following to be able to be
    true:
    LS.equals(L)
    LS.equals(S)
    However, symmetry and transitivity combine to tell us
    that L.equals(S) and S.equals(L) must also return
    true.
    The contracts for List and Set require L.equals(S)
    and S.equals(L) to return false.
    Ah ok. Thanks for clearing that up for me. It seems kind of limiting to say that there could never be a collection that is both a list and a set, but I guess it wouldn't be too hard to work around.
    Object and arrays use the same equals method--only
    returns true if the references are equal.Yes, I meant Object in the general sense, not the Object class itself. So things like Integer(5) can be equal to another Integer, but never to a Float.
    There's List and Set where all lists and
    sets are equal to other lists and setrespectively,
    No. Any List can be equal to any other List,
    and any Set can be equal to any other Set. In
    both cases, it depends on what elements the
    collection contains.Right, sorry that's what I meant to say.
    It makes sense that List and Set define equals the
    way they do. Since Lists are ordered, it makes sense
    that the order should matter in determining equality.
    Since Sets are not ordered, it would not make
    sense to use order in determining equality.Naturally. But it might also make sense just to say that lists and sets are only equal to themselves.
    and there's the CharSequence pattern in which all
    bets are off.There's nothing special about CharSequence. It's just
    another interface that doesn't define a specific
    equals implementation.Yes. What I was trying to get at is that while in general objects (such as subclasses of Number) are only be equal to objects of the same class, and lists and sets must be equal to other lists and sets, respectively, that CharSequence says that some subclasses MAY be comparable using equals.
    However, ease of learning is not the one and only
    supreme driving force behind the design of the
    language and the APIs.Acknoledged. What I mean is that with equals following all these different patterns, it is easy to make a mistake that goes unnoticed until software is in the hands of the clients.
    Rather than trying to cram equals (or anything else)
    into a fixed set of pigeonholes, you'd be better
    served to try to undertand the fundamental purpose
    behind it and what kinds of factors go into deciding
    what the appropriate implementation is in a given
    situation.Ok. What is the fundamental purpose behind equals? Not trying to be hostile here, I'm just curious. I know that one of the biggest factors is with collections and such questions as hashing and contains. Another big one is String.equals(...) to compare strings. Are there any others?
    I'm just trying to figure out how it might be possible to make equals() more opaque in future languages, so that people can read the basic definition of equals given in Object and know how it is used and how to use it. If you think that it is already clear and easy to use, consider that using FindBugs (google for FindBugs if you are interested) I found a bug in the java source in ChoiceFormat that has existed since ChoiceFormat's inception in Java 1.1 in which it calls equals between a StringBuffer and a String. If the people working on designing Java can make these mistakes, what hope have the rest of us?

  • Implements Comparable

    I am trying to create a holder object, which holds two values. It is called TwoTuple. I implemented Comparable so that I can use it in a Set.
    public class TwoTuple<A,B> implements  Comparable<TwoTuple>{
         public final String first;
         public final B second;
         public TwoTuple(String first, B b){
              this.first = first;
              second = b;
         public int compareTo(TwoTuple tt){
                     int result = first.compareTo(tt.first);
                     return result;
         public String toString(){
              return "Variable == " + first + "  Value == " + second;
    }This is my test class:
    public class Test{
         private static Set<TwoTuple> state = new HashSet<TwoTuple>();
         public static void main(String[] args){
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              for(TwoTuple tt : state)
                   System.out.println(tt);
    }Output:
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Variable == Testing  Value == trueWhy am I still getting 3 of the same elements in this Set?

    This doesn't address the hash code issue, but here's an implementation of equals() for a similar class I have called Pair. It's generic & takes two objects F & S (first & second). Might apply to what you're doing, or may not.
    @Override public boolean equals(final Object object) {
         if (this == object) {
              return true;
         if (object == null) {
              return false;
         if (getClass() != object.getClass()) {
              return false;
         @SuppressWarnings("unchecked")
         final Pair<F,S> other = (Pair<F,S>)object;
         if (first == null) {
              if (other.first != null) {
                   return false;
         } else if (!first.equals(other.first)) {
              return false;
         if (second == null) {
              if (other.second != null) {
                   return false;
         } else if (!second.equals(other.second)) {
              return false;
         return true;
    }

  • GetClass() vs. Instanceof in equals()

    As we know there are differing opinions on what is better to use in overriding equals(). getClass() or instanceof for
    argument type checking.
    I would like to know if there is anyoneone who is strongly in favor of using instanceof instead of getClass()?

    It depends on the semantics of your types. You need to be aware that getClass() only gives equality if the two classes are identical, whereas instanceof works for subtype. For example, if you have an ArrayList, then instanceof Object, instanceof List, instanceof ArrayList, and instanceof a bunch of other supertypes all give true.
    If two objects of different classes can be equal, then use instanceof. But once you use instanceof at some level in the class hierarchy, everything below it must use instanceof, or you'll violate the symmetry clause of the equals contract. For example, any List can be equal to any other List, as long as they have the same elements in the same order. So any List implementation's equals() method must do instanceof List, not getClass() and then compare to its own class.
    If, on the other hand, it only makes sense for an instance of class X to be equal to another instance of exactly class X (and not to any subclass), then use getClass().

  • Getting equals() right with interfaces???

    How can one make sure that objects that implement some interface use one's own implementation of equals() for comparison?
    The problem is this: the client programs against an API that defines interfaces for certain kinds of objects, and a factory to return objects that implement that interface somehow, without the client needing to know how.
    Now how can the implementation make sure that any object that gets compared by the client uses an implementation-specific version of equals instead the one inherited from Object?
    So far my understanding of things is that this is not possible, but when I look at how enormous the problem is, I cannot imagine that there is no solution at all.
    So to give a more concrete example: let's say the API defines interface SomeInterface and there is some (factory) method that returns objects to the client that somehow implement SomeInterface. Now when the client has two objects o1 and o2 both implementing SomeInterface, I want to make sure that o1.equals(o2) uses an implementation dependend method of comparing things. However, since the client does not need to know which implementation is used (and indeed that might even change between runs or different versions of the implementation library) I do not want the client to downcast to an implementation-specific type.
    Is there any way, trick or workaround to get equals() comparisons to work?

    johann_p wrote:
    georgemc wrote:
    Can't be done. I can't see the real need anyway. It's up to classes to ensure they implement equals themselves, if they need to. Why do you need programming tricks to ensure that you write your code properly? If you've got issues with classes possibly not having implemented equals "properly", something's wrong. Hmmm, I wonder how you can not see the need :
    I do not think that my situation is so exotic really: somebody wants to provide an API that returns objects. The client programs against an interface for these objects but does not want to care about the implementation. Now at some point client simply wants to compare two objects client got from the API to see if they are equal(). Or just wants to add them to a set. This should just work correctly without the client needing to know about the implementation, right?
    How do people solve this problem in general? The only way out I see (thank you tjacobs01 for confirming this) is an abstract class to inherit from but this only works if the implementation classes do not need to inherit from some other class already. Right. You say it yourself: client code need not know about the implementation. Can you give a concrete example of the problem, as you're experiencing it?
    >>
    If you need to arbitrarily change comparisons, you could use Comparators, though.I am not sure I can follow you here -- that still won't make equals() and hashCode() work in the way the API client would need it for e.g. using HashSets of these objects correctly.Correct, it circumvents equals altogether. Writing code that ensures you've implemented hashCode and equals properly - if it could be done - would be more difficult than implementing those methods correctly. I'd focus on getting those methods right, and ensuring they're well-tested

  • MyInteger class- compile error - method doesnt implement comparable method

    I am trying to test how the code for a hash table works- I have 4 classes
    Hashable interface
    QuadraticProbableHashTable
    HashEntry
    MyInteger
    Everything is compiling but one error comes up saying that "Class must implement the inherited abstract method Comparable.compareTo(object)."
    I have a comparable method with the same signature as that in Comparable interface; in MyInteger.java where the problem is. However I still have the same problem.
         * Wrapper class for use with generic data structures.
         * Mimics Integer.
        public final class MyInteger implements Comparable, Hashable
             * Construct the MyInteger object with initial value 0.
            public MyInteger( )
                this( 0 );
             * Construct the MyInteger object.
             * @param x the initial value.
            public MyInteger( int x )
                value = x;
             * Gets the stored int value.
             * @return the stored value.
            public int intValue( )
                return value;
             * Implements the toString method.
             * @return the String representation.
            public String toString( )
                return Integer.toString( value );
             * Implements the compareTo method.
             * @param rhs the other MyInteger object.
             * @return 0 if two objects are equal;
             *     less than zero if this object is smaller;
             *     greater than zero if this object is larger.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public int compareTo( Comparable rhs )
                return value < ((MyInteger)rhs).value ? -1 :
                       value == ((MyInteger)rhs).value ? 0 : 1;
             * Implements the equals method.
             * @param rhs the second MyInteger.
             * @return true if the objects are equal, false otherwise.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public boolean equals( Object rhs )
                return rhs != null && value == ((MyInteger)rhs).value;
             * Implements the hash method.
             * @param tableSize the hash table size.
             * @return a number between 0 and tableSize-1.
            public int hash( int tableSize )
                if( value < 0 )
                    return -value % tableSize;
                else
                    return value % tableSize;
            private int value;
        }

    >
    You might want to also allow for cases where the
    value passed in is null, or the argument to the
    method is NOT a MyInteger object :-)
    Just a small note - the javadocs for Comparable#compareTo says the following:
    Throws:
    ClassCastException - if the specified object's type prevents it from being compared to this Object.
    So it's perfectly OK to blindly try to cast to the desired type in the sense that you are not violating the Comparable contract if the cast fails.

  • Custom equality comparison

    Hi All,
    I have an Object lets say its named "Bomb".Bomb has two member variables x and y both Strings.
    public class Bomb {
    String x;
    Stirng y;
    I have a HashMap that holds these Bomb objects as keys , and values as some other objects.
    HashMap
    | Bomb | some object |
    In the class Bomb, either the value of x, or the value of y can be null, but not both.
    The HashMap is populated with Bomb objects that have non-null values for both x and y.
    How do i implement the equals and hashCode() for the Bomb Object so that I can lookup the value within the HashMap using a Bomb object that has only one of x or y that is non-null.
    For instance, in the HashMap , I cd have a Bomb object whose x="hello" and y="world", and i lookup with a Bomb object whose x is null and y = "world", i shd be able to get the value within the HashMap. Similar is the case where x is not null and y is null.
    any clues ?

    This sounds like a very bad idea.
    If you have {"Hello", "world"} in the map, you want be able to find it with {"Hello", null} and also with {null, "world"} right?
    This means that {"Hello", "world"} must equal {"Hello", null} and {"Hello", "world"} must also equal {null, "world"}.
    But this means that {"Hello", null} and also with {null, "world"}.
    Also, {"Hello", "booger"} would be equal to {"Hello", null}, and therefore {"Hello", "booger"} would be equal to {"Hello", "world"} and to {null, "world"}.
    I'd suggest you create two maps. One would have a Comparator that compares just the first field, and one would have a comparator that compares just the second field.

  • HashSet doesnt remove duplicates

    Hello
    I am trying to remove duplicates from a list using this code
    Set set = new HashSet();
    ListIterator li = list.listIterator();
    while (li.hasNext())
                   A pt = (A) li.next();
                   duplicate = pt.getID(); //duplicate is declared globally
                    if (!set.add(pt))
                        System.out.println("Duplicate found: " + pt.getID());
               }but it isnt removing duplicates. I read somewhere that I should override the equals() and hashCode() methods. But I am a bit confused as to how to write my equals method. The list contains objects of class A, which has many getters and setters. The elements are considered to be duplicate when getID() getter returns same value for two objects. Can some one tell me how should i go about writing the equals method. And why the default equals method for objects isnt working in this case?
    This is how i tried to write my equals() method but it isnt working
    public boolean equals(Object o)
           if (o == this)
                 return true;
            if (!(o instanceof A))
                 return false;
            A pn =  (A) o;
            return pn.getID() == duplicate; // duplicate has been set before calling add
         }

    Sorry if I got confusing about what I was trying to say. I was actually trying to expand on your earlier post, where you mentioned that the class needs the proper implementation of equals() had hashCode().
    I went over this with one of my programmers fairly recently. He was having a hard time understanding why he was getting a false when the contents of the object were the same. Of course he did not override the equals() method and was doing an object comparison, and not one on the contents of the objects.
    Maybe the following examples will better illustrate what I was trying to say.
    Without equals:
    public class EqualityExample {
         public EqualityExample()
          * @param args
         public static void main(String[] args) {
              EqualityExample ee = new EqualityExample();
              // TODO Auto-generated method stub
              DataClass testObject1 = ee.new DataClass("A String");
              DataClass testObject2 = ee.new DataClass("A String");
              if (testObject1.equals(testObject2))
                   System.out.println("are equal");
              else
                   System.out.println("not equal");
         public class DataClass
              private String someVal;
              public DataClass(String someVal)
                   this.someVal = someVal;
    }With equals:
    public class EqualityExample {
         public EqualityExample()
          * @param args
         public static void main(String[] args) {
              EqualityExample ee = new EqualityExample();
              // TODO Auto-generated method stub
              DataClass testObject1 = ee.new DataClass("A String");
              DataClass testObject2 = ee.new DataClass("A String");
              if (testObject1.equals(testObject2))
                   System.out.println("are equal");
              else
                   System.out.println("not equal");
         public class DataClass
              private String someVal;
              public DataClass(String someVal)
                   this.someVal = someVal;
              public boolean equals(DataClass object)
                   if (object.someVal == this.someVal)
                        return true;
                   else
                        return false;
    }

  • H:selectOneMenu and converter problem

    Hello
    I'm working on an application (Address Database) using JSF (Base JSF libs with IBM Faces). Apache Tomcat Server 5.5.
    Since days i'm trying to solve my problem with h:selectOneMenu and converter. I can save values correctly, but i cannot display the saved value again as a selected item.
    so here is my jsf code section:
         <h:selectOneMenu value="#{personBean.person.representative}"
                        styleClass="fldDefault fldcombo">
                        <f:selectItems value="#{partnerBean.representatives}" />
                        <f:converter converterId="keywordConvertor" />
                        <f:attribute name="SelectItemArrayList"
                             value="#{partnerBean.representatives}" />
         </h:selectOneMenu>
    representatives are keywords and in the selectOneMenu, a representative keyword object is stored.
    here is my partnerBean.jsp Code:
         private List<SelectItem> representatives = null;
         * populate keywords of type REPRESENTATIVE
         public void populateRepresentatives() {
              representatives = new ArrayList<SelectItem>();
              ArrayList<Keyword> representativeKeywords = kwHandler
                        .getKeywordsByType(KW_REPRESENTATIVE_TYPE);
              for (Keyword keyword : representativeKeywords) {
                   representatives.add(new SelectItem(keyword, keyword
                             .getKwDescription()));
    so the function gets the representative keyword objects, loop through them and add a newly created SelectItem Object to the representatives list.
    There is a converter in order to save and display (should!!) the values:
    public class KeywordConvertor implements Converter {
         public Object getAsObject(FacesContext context, UIComponent component,
                   String value) {
    ....code for saving...
         public String getAsString(FacesContext context, UIComponent component,
                   Object obj) {
    `          System.out.println(((Keyword) obj).getId()+"");
              return ((Keyword) obj).getId()+"";
    i did not provide the code for getAsObject, since the saving of the combo box works fine. If it has to do something with my problem, please ask me for this code..
    The System.out.prinln prints all ids correctly, but the generated HTML Code does not select the given value in the combobox.
    So whats wrong with the getAsString Method? or is the function completely somewhere else?
    I have to say that the function ((Keyword) obj).getId() returns a long !! is that the problem?
    Any help is very appreciated

    Hello
    i implemented the function in the Keyword Class:
    public class Keyword implements Serializable {
         public boolean equals(Keyword kw) {
              System.out.println("calling equals in:" + kw.getId());
              if (kw.getId() == this.getId()) {
                   return true;
              } else {
                   return false;
    but the System.out.print is not executed...
    i tried also:
         public boolean equals(Object o) {
              Keyword kw = (Keyword) o;
              System.out.println("calling equals in:" + kw.getId());
              if (kw.getId() == this.getId()) {
                   return true;
              } else {
                   return false;
    but then i get the following error message:
    org.apache.jasper.JasperException: javax.servlet.jsp.JspException: could not initialize proxy - no Session
    hmmm, could you show me how to implement the equals Function correctly?

Maybe you are looking for

  • Is this Cf or CSS causing problem?

    I am on the home stretch on this job. I have this one irritating problem and I am not sure if the prob is being caused by a <cfinput> tag or a style sheet problem. Maybe someone out there can help identify what's happening. My guess is that it is in

  • Random Visio Stencils Displaying Only as Black and White Lines (No colour)

    I'm experiencing a strange problem where some Visio stencils/shapes are displaying only as black and white outlines (i.e. - without any colour). I'm using Visio 2010 on a Samsung NC900 laptop with 8gb RAM, 1.7Ghz i7 CPU on Windows 7. The symptoms tha

  • Need Help Importing CD's!

    I recently bought a new iPod and when I put a cd into the computer, iTunes will not recognizing the CD (these are brand new cd's and are not burned). I share a computer with my roommate and I do not have adminstrative rights, but this has not been a

  • My e mail page is frozen  when I en it in the iPad. Any ideas?

    My e mail page is frozen in my iPad. Everything else is working right, but the mail page is frozen. Any ideas?..

  • How to OCR a page after applying a header?

    Hi all, Acrobat X 10.1.3 pro & standard: I get this error message "Acrobat could not perform recognition (OCR) on this page because: This page contains renderable text." The only "renderable text" is a page number I applied to the top of the page. Th