- import java.util.*;
- class HashtableDemo
- {
- public static void main(String[] args)
- {
- Set<RectangleTest> set=new HashSet<RectangleTest>();
- RectangleTest rect1=new RectangleTest(3,4);
- RectangleTest rect2=new RectangleTest(4,5);
- RectangleTest rect3=new RectangleTest(3,4);
- RectangleTest rect4=new RectangleTest(5,7);
- set.add(rect1);
- set.add(rect2);
- set.add(rect3);
- set.add(rect4);
- System.out.println(set.size());
- rect4.width=7;
- System.out.println(set.contains(rect2));
- System.out.println(set.contains(rect4));
- // System.out.println(set.remove(rect4));
- System.out.println(set.size());
- }
- }
- class RectangleTest
- {
- public int width;
- public int height;
- public RectangleTest(int width,int height)
- {
- this.width=width;
- this.height=height;
- }
- public boolean equals(Object obj)
- {
- if(this==obj)
- return true;
- if(obj==null)
- return false;
- if(getClass()==obj.getClass())
- return true;
- RectangleTest rect=(RectangleTest)obj;
- if(width!=rect.width)
- return false;
- if(height!=rect.height)
- return false;
- return true;
- }
- public int hashCode()
- {
- final int prim=31;
- int result=1;
- result=prim*result+width;
- result=prim*result+height;
- return result;
- }
- }
复制代码
|
|