override equals and hash code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mickey0
    New Member
    • Jan 2008
    • 142

    override equals and hash code

    Hello,
    my situation is this below; not sure about what override; I guess I must override 'Point'; In general, do I need to override Object1 as well?

    Code:
    class Figure {
      public Set<Point> points = new HashSet<Point>();
    }
    
    class Point {
      String name;
      public List<Object1> coll = new ArrayList<Object1>();
    }
    
    class Object1  {
        String type;
        String code;
    }
    Moreover: in my case two points are equal if and only if they have just the same 'name'; So I suppose that can I cut something of the stuff that Eclipse generates automatically; but do I still need to override hashCode? (even I just need to compare 'name')?
    thanks,
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    Mickey,

    You really should override hashCode, yes.

    Especially if you're going to use the objects with the standard containers in java.util. These containers use the hashcode for a fair number of things.

    If you want, you can cheap out and just return zero for all objects. This will assure that your objects will work correctly --- at the expense of serious performance degradation when using any of the containers which uses hashing.

    Hopefully that makes a little sense.

    Comment

    Working...