黑马程序员_ArrayList_HashSet及Hashcode的分析

----------- android培训java培训、java学习型技术博客、期待与您交流! ------------ 

首先,我们都知道ArrayList是有序集合,相当于数组。存放的是外面对象的引用。这里对象可以重复。而HashSet存放的对象不能重复。

设计一个程序来详细说明,ArrayListHashSet的区别:

public class ReflectPoint {

 public int x;

 public int y;

 public ReflectPoint(int x, int y) {

  super();

  this.x = x;

  this.y = y;

 }

 @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;

  ReflectPoint other = (ReflectPoint) obj;

  if (x != other.x)

   return false;

  if (y != other.y)

   return false;

  return true;

 }

}

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashSet;

public class ReflectTest2 {

 

 public static void main(String[] args) {

  //Collection collection=new ArrayList();   //ArrayList可以放入相同的对象的引用打印----4

  Collection collection=new HashSet();   //不能放入相同对象的引用  打印----3

  ReflectPoint point1=new ReflectPoint(1, 1);

  ReflectPoint point2=new ReflectPoint(1, 2);

  ReflectPoint point3=new ReflectPoint(1, 1);   //reflectpoint中生成HashCodeequals,这个点将放不进去 打印---2

  collection.add(point1);

  collection.add(point2);

  collection.add(point3);

  collection.add(point1);

  point1.y=4;       //修改y后,下面的point1就删不掉,因为内存泄露。这样证明java中有内存泄露

  collection.remove(point1); 

  System.out.println(collection.size());

 }

}

其中有关HashCode的问题:

hashcode把集合分为若干值域,把将要存入的数据转化为HashCode值后放入不同的区域,

当对象被存储进HashCode集合中以后,就不能修改这个对象中的那些参与计算哈希值得字段了,否则,对象修改后的哈希值与最近存储进HashSet集合中时的哈希值就不同了,在这种情况下,即使在contains 方法使用该对象当前的引用作为参数去HashSet集合检索对象,也将返回找不到对象的结果,这也会导致无法从HashSet集合中单独删除当前对象,从而造成内存泄露。


----------------------- android培训java培训、java学习型技术博客、期待与您交流! ----------------------

详情请查看:http://edu.csdn.net/heima


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值