CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2013

    Hash Set Question

    I am analysing a particular code and have some questions
    public class Point {   
        private final int x;   
        private final int y;   
        public Point(int x, int y) {   
            this.x = x;   
            this.y = y;   
    import java.util.HashSet;   
    import java.util.Set;   
    public class PointMain {   
        public static void main(String args[]){   
            System.out.println(onUnitCircle(new Point(1, 0)));   
        // Initialize UnitCircle to contain all Points on the unit circle   
        private static final Set<Point> unitCircle;   
        static {   
            unitCircle = new HashSet<Point>();   
            unitCircle.add(new Point( 1,  0));   
            unitCircle.add(new Point( 0,  1));   
            unitCircle.add(new Point(-1,  0));   
            unitCircle.add(new Point( 0, -1));   
        public static boolean onUnitCircle(Point p) {   
            return unitCircle.contains(p);   
    I get a false when i do a contains on a hashset. I am thinking that it should yield true.
    The question i had was that without overriding the equals or the hashcode when i store the values in a Hash Set and do a contains i am assuming that it might have the equals and hashcode implemented. Would this be correct then- when i am using the hash set to store my objects the right way to use the contains is that i implement a hashcode and a equals method in object that i am going to do the contains on?


  2. #2
    Join Date
    Jul 2013

    Re: Hash Set Question

    Quote Originally Posted by frankyfish View Post
    without overriding the equals or the hashcode
    You must supply equals and hashCode methods in Point. Otherwise it won't work with the standard hash based collections, such as HashSet.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.