HashSet与LinkedHashSet

HashSetTest.java

package com.collection;

import java.util.HashSet;

public class HashSetTest {
 public static void main(String[] args) {
  //此处容量会自动增到到2的倍数,增到4
  HashSet<String> set = new HashSet<String>(3);
  set.add("a");
  set.add("b");
  set.add("c");
  set.add("d");
  set.add("e");//这个时候set底层会创建一个长度为8的数组
               //原来长度为4的数组会编程垃圾,等待回收
  System.out.println(set);
  
 }

}

 

HashSetTest2.java

package com.collection;

import java.util.HashSet;

class A{
 private int count;
 public A(int count){
  this.count = count;
 } 


 public boolean equals(Object obj){
  if(this == obj)
   return true;
  if((obj != null) && (obj.getClass() == A.class)){
   A targetobj = (A)obj;
   //如果两个对象的关键属性相同
   if(this.count == targetobj.count)
    return true;
  }
  return false;
 }


 //当我们要把元素存入哈希表(HashSet/HashMap)时,
 //此时应该重写hashCode方法
 //hashCode不要写成了HashCode
 public int hashCode(){
  
  return 20;
 }
}


public class HashSetTest2 {
 public static void main(String[] args) {
  
  HashSet<A> set = new HashSet<A>();
  set.add(new A(2));
  set.add(new A(2));
  System.out.println(set);
  
 }
}

 

HashSet存储顺序跟添加顺序不一致。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值