1. 程式人生 > >繼承Set介面類過載equals方法和hashCode方法

繼承Set介面類過載equals方法和hashCode方法

所用Set定義的
         當存的資料相同時,(不管地址是否相同)就認為存的是一個數據

public void test0() {
			Set c = new HashSet();
			String t1 = "11111";
			String t2 = "11111";
			String t3 = new String("11111");
	    	c.add(t1);
	    	c.add(t2);
	    	c.add(t3);
	    	System.out.println(c.size());
		}

結果為:1

呼叫其他類來輸入值時,計算機不能判斷值是否相等
         但是可以在呼叫的類中過載equals方法和hashCode方法(來進行判斷值是否相等)

@Test
	    public void test1() {
	    	Set c = new HashSet();
	    	c.add(new Student("行",20));
	    	c.add(new Student("行",20));
	    	c.add(new Student("行",20));
	    	System.out.println(c.size());
	    }
	    

沒過載equals方法和hashCode方法時結果為3,過載equals方法和hashCode方法後結果為1

public class Student {
	
		public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
		private String name = null;
		private int age;
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + age;
			result = prime * result + ((name == null) ? 0 : name.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Student other = (Student) obj;
			if (age != other.age)
				return false;
			if (name == null) {
				if (other.name != null)
					return false;
			} else if (!name.equals(other.name))
				return false;
			return true;
		}
}

 

List定義的類,即輸入的個數

public void test6() {
			List c = new LinkedList();
			String t1 = "11111";
			String t2 = "11111";
			String t3 = new String("11111");
	    	c.add(t1);
	    	c.add(t2);
	    	c.add(t3);
	    	System.out.println(c.size());
		}

結果為:3

public void test8() {
	    	List c = new LinkedList();
	    	c.add(new Student("行",20));
	    	c.add(new Student("行",20));
	    	c.add(new Student("行",20));
	    	System.out.println(c.size());
	    }

結果為:3