Java隨機4-Hashset

來源:互聯網
上載者:User
package com.broadengate.fangxing;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;/** * 應該都知道 hashset 不允許放入重複的資料,那麼他是根據什麼來判斷是否是重複的資料呢? * 在hashset中用到了hash演算法,因為hashset底層也是用的Hashmap來存取資料 * ,在hashmap底層則是用的數組來存取,而在hashmap放資料的時候會用到hashcode * ,這就是hashmap存入的資料沒有順序的原因,他就是根據hashcode來存放的 *  * 如果不重寫hashcode 則預設是使用Object裡面的,是根據對象的引用地址來產生的hashcode,所以在沒建立一個對象的時候他的引用地址都不一樣, *  */public class HashCodeTest {public static void main(String[] args) {HashCodeTest hashCodeTest = new HashCodeTest();Collection coll = new /* ArrayList() */HashSet();Person person = hashCodeTest.new Person("1", 1);Person person1 = hashCodeTest.new Person("1", 1);Person person2 = hashCodeTest.new Person("1", 1);Person person3 = hashCodeTest.new Person("1", 1);Person person4 = hashCodeTest.new Person("1", 1);Person person5 = hashCodeTest.new Person("1", 1);coll.add(person5);coll.add(person4);coll.add(person);coll.add(person2);coll.add(person3);coll.add(person1);// 如果重寫了hashcode方法和eq方法, 如果這裡把放入記憶體中的對象的值改變,則他的hashcode值就會變,// jvm在根據hashcode算出來的地區去找person對象就找不到那個對象,所以就不能移除person.setAge(2);coll.remove(person);System.out.println(coll.size());}class Person {private String name;private int age;public Person() {}public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}/** * @Override public int hashCode() { final int prime = 31; int result = *           1; result = prime * result + getOuterType().hashCode(); *           result = prime * result + age; result = prime * result + *           ((name == null) ? 0 : name.hashCode()); return result; } * @Override public boolean equals(Object obj) { if (this == obj) return *           true; if (obj == null) return false; if (getClass() != *           obj.getClass()) return false; Person other = (Person) obj; *           if (!getOuterType().equals(other.getOuterType())) return *           false; if (age != other.age) return false; if (name == *           null) { if (other.name != null) return false; } else if *           (!name.equals(other.name)) return false; return true; } *  *           private HashCodeTest getOuterType() { return *           HashCodeTest.this; } **/}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.