ArrayList和HashSet对的比较及HasCode分析

实例代码:
ReflectPoint.java文件代码:

package cn.yzx.day1;

public class ReflectPoint {
   private int x;
   public int y;
   public String str1 = "ball";
   public String str2 = "basketball";
   public String str3 = "itcast";

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

   @Override
   public String  toString()
   {
      return str1 + ":" + str2 + ":" + str3;
   }

}

ReflectTest2.java文件代码:

package cn.yzx.day1;

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

public class ReflectTest2 {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Collection collections = new ArrayList();
      ReflectPoint pt1 = new ReflectPoint(3, 3);
      ReflectPoint pt2 = new ReflectPoint(5, 5);
      ReflectPoint pt3 = new ReflectPoint(3, 3);
      collections.add(pt1);
      collections.add(pt2);
      collections.add(pt3);
      collections.add(pt1);

      Collection collections1 = new HashSet();
      collections1.add(pt1);
      collections1.add(pt2);
      collections1.add(pt3);
      collections1.add(pt1);

      //下面两行代码不注释结果为1,只是后结果为2


      System.out.println(collections.size());
      System.out.println(collections1.size());

      //从打印可以看出ArrayList在内存中存放时不考虑对象是否相同,
      //但用HashSet就会考虑对象是否相同,当实现了hashCode(在ReflectPoint类中,当然重载了hashCode也要重载equals)方法时,
      //那么不同对象相同的元素的值相同也只存储一次。从上面注释的两行代码可以看出,当用HashSet集合存储后不应该修改元素的值,要不然指向的
      //对象就会丢失,就会造成内存泄露
   }

}

运行结果:

从打印可以看出ArrayList在内存中存放时不考虑对象是否相同,但用HashSet就会考虑对象是否相同,当实现了hashCode(在ReflectPoint类中,当然重载了hashCode也要重载equals)方法时,那么不同对象相同的元素的值相同也只存储一次。从上面注释的两行代码可以看出,当用HashSet集合存储后不应该修改元素的值,要不然指向的对象就会丢失,就会造成内存泄露。

你可能感兴趣的:(String,hashset,ArrayList)