for java beginner 14 ArrayList HashSet HashCode(中)

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


}

}

------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值