Collection & set
来源:互联网 发布:dnf一上线就网络中断 编辑:程序博客网 时间:2024/05/17 08:16
package test;import java.util.HashSet;import java.util.Iterator;public class HashDemo {/** * |--set :元素是无序的(存入和取出的顺序不一定一致),元素不可以重复 * |--HashSet:底层数据结构是哈希表 * HashSet是如何保证元素唯一性的呢? * 通过元素的两个方法,hashCode和equals来完成 * 如果元素的hashCode值相同,才会判断equals是否为true * 如果元素的hashCode值不同,不会调用equals * 对于判断元素是否存在,以及删除等操作,依赖的方法是元素 的hashCode(先)和equals(后)方法 * (ArrayList 依赖的是equals方法) * |--TreeSet: */public static void main(String[] args) { HashSet hs = new HashSet(); sop(hs.add(new Person("a1","11")));//true add方法返回类型是 boolean sop(hs.add(new Person("a2","12")));//true sop(hs.add(new Person("a3","13")));//true Iterator it =hs.iterator(); while(it.hasNext()){ Person p =(Person)it.next(); sop(p.getName()+"||"+p.getAge()); } /* a1--hashcode--30561568 true a2--hashcode--30571569 true a3--hashcode--30581570 true a2--hashcode--30571569 a2|euqals|12 false a3||13 a1||11 a2||12 */ sop(hs.contains(new Person("a1","11"))); /* a1--hashcode--30561568 a1|euqals|11 true */ sop(hs.remove(new Person("a2", "12"))); /* a2--hashcode--30571569 a2|euqals|12 true */ }public static void sop (Object obj){ System.out.println(obj);}}
class Person {private String name;private String age;Person(String name,String age){ this.name=name; this.age=age;}public String getName() { return name;}public void setName(String name) { this.name = name;}public String getAge() { return age;}public void setAge(String age) { this.age = age;}/**对象复写hashcode和俄equals方法*/public boolean equals(Object obj){ if(!(obj instanceof Person)){ return false; } Person p =(Person)obj; System.out.println(this.name+"|euqals|"+this.age); return this.name.equals(p.name);}public int hashCode(){ System.out.println(this.name+"--hashcode--"+ name.hashCode()+age.hashCode()); return name.hashCode()+age.hashCode();}}
0 0
- Collection & set
- Collection List Set Map
- Set in Java Collection
- collection list set
- Collection/List/Set
- Collection(四) Set
- Collection Map Set
- Collection集合之Set
- collection,list,set,map
- Collection、List、Set、Map
- Collection:Set集合
- 【java】collection-->set
- Collection--Set--hashSet
- collection--set--treeSet
- set collection list
- Java-Collection-Set
- Collection之Set集合
- java-Collection(List、Set)
- 理想倍频器/分频器对相噪/杂散的影响
- 指向指针的指针的一种用法
- 汇编学习(二)
- 电子邮件
- Android学习进阶路线导航线路
- Collection & set
- [leetcode-11]container with most water(C)
- Java面向对象之继承
- LeetCode 226Isomorphic Strings
- 每天一个linux命令(11):nl命令
- 算阶乘
- IOS中关闭滚动条
- Java中接口与多态
- 2015-07-26总结