国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Hashset 使用不當引起的內存泄漏

2019-11-11 03:56:09
字體:
來源:轉載
供稿:網友

修改hashset中對象的屬性值,且屬性值是計算哈希值的字段,這時會引起內存泄漏

即:當一個對象被存儲進HashSet集合中以后,就不能修改該對象的參與計算哈希值的屬性值了 ,否則對象修改后的哈希值與最初存儲進HashSet集合中時的哈希值就不同了,在這種情況下,即使在contains方法使用該對象的當前引用作為參數去HashSet集合中檢索對象,也將返回找不到對象的結果,這也會導致無法從HashSet集合中刪除當前對象,造成內存泄露。

舉例說明:

public class HashSetTest { public static void main(String[] args) { Set<Person> set = new HashSet<Person>(); Person p1 = new Person("唐僧", "pwd1", 25); Person p2 = new Person("孫悟空", "pwd2", 26); Person p3 = new Person("豬八戒", "pwd3", 27); set.add(p1); set.add(p2); set.add(p3); System.out.Word; private int age; public Person(String username, String password, int age) { this.username = username; this.password = password; this.age = age; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } 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 + age; result = prime * result + ((password == null) ? 0 : password.hashCode()); result = prime * result + ((username == null) ? 0 : username.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 (age != other.age) return false; if (password == null) { if (other.password != null) return false; } else if (!password.equals(other.password)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return this.username + "-->" + this.password + "-->" + this.age; }}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 广元市| 永安市| 溧水县| 交口县| 南雄市| 古蔺县| 广平县| 如皋市| 舟山市| 榆树市| 吉林市| 凌海市| 工布江达县| 伊通| 元阳县| 工布江达县| 晋宁县| 仙居县| 吴堡县| 苗栗县| 庆云县| 乌兰察布市| 二连浩特市| 米林县| 新巴尔虎右旗| 西乌珠穆沁旗| 民权县| 石台县| 忻州市| 甘南县| 海宁市| 洛南县| 荣成市| 顺昌县| 安多县| 东乡县| 剑阁县| 广东省| 盐边县| 阿图什市| 祁阳县|