`
hubin4
  • 浏览: 92974 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

for java beginner 14 ArrayList HashSet HashCode(中)

    博客分类:
  • JAVA
阅读更多
java 反射 数组的反射

ArrayList HashSet HashCode
---------------------------------
package com.ncs;

public class Point {

	

	private int x;
	public int y;
	
	public  String s1 ="ball";
	public String s2="hubin";
	public String s3="zhangxiaoxiang";
	//做实验而已,字段不可能是 public 的
	
	public Point(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	//这里来两个方法有时注释,有时没有注释,注意哦
	//这两个覆盖方法ECLIPSE有菜单的
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + x;
		result = prime * result + y;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Point other = (Point) obj;
		if (x != other.x)
			return false;
		if (y != other.y)
			return false;
		return true;
	}
	
}

-----------------------------------
package com.ncs;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class MyHashTest {

	public static void main(String[] args) {
		Point p1 = new Point(3,3);
		Point p2 = new Point(5,5);
		Point p3 = new Point(3,3); //看看和 p1有什么不一样
	
		Collection collection1 = new ArrayList();
		Collection collection2 = new HashSet();
		
		collection1.add(p1);
		System.out.println(collection1.size()); //1
		collection1.remove(p3);
		System.out.println(collection1.size()); //0 写了equals 和 hashcode了呀
		//我把int hashCode()去掉,还是老样子,因为是ArrayList,才不管你 哈稀值呢!!
		
		//但是我把public boolean equals(Object obj) 去了,哪就不一样了
		//1 1 了所以ArrayList 只和equals有关
		
		//再来
		collection1.add(p2);
		System.out.println(collection1.size()); //2,上面测试时留下的1个也在里面
		p2.y = 10; //修改里面的值
		collection1.remove(p2);
		System.out.println(collection1.size()); //1,即使修改了值,还是去了,因为P2指向不变
		//p2内存地址不变
		
		System.out.println("**************************");
		//看看hashset
		collection2.add(p1);
		collection2.add(p2);
		collection2.add(p3);
		collection2.add(p1);
		
		System.out.println(collection2.size()); //2 说你一样的加不进的
		//去掉 int hashCode(),就是3了,
		
		collection2.clear();
		System.out.println(collection2.size()); //0
		
		collection2.add(p1);
		p1.y=10; //修改了后,hashset就找不到了,不可以删除
		collection2.remove(p1);
		System.out.println(collection2.size()); //1
		
		//---------
		String s1 ="BB";
		String s2 = "Aa";
		
		System.out.println(s1.hashCode());//2112
		System.out.println(s2.hashCode());//2112
		
		
	}

}

------------------------------
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics