程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> java- (c.remove(new Name(f1,l1)));為什麼沒被移除

java- (c.remove(new Name(f1,l1)));為什麼沒被移除

編輯:編程綜合問答
(c.remove(new Name("f1","l1")));為什麼沒被移除

import java.util.*;

public class BasicContainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println
(c.remove(new Name("f1","l1")));
System.out.println(c);
}

}

class Name implements Comparable {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }

public boolean equals(Object obj) {
    if (obj instanceof Name) {
        Name name = (Name) obj;
        return (firstName.equals(name.firstName))
            && (lastName.equals(name.lastName));
    }
    return super.equals(obj);
    }
    public int hashCode() {
        return firstName.hashCode();
    }



    public int compareTo(Object o) {
    Name n = (Name)o;
    int lastCmp = 
        lastName.compareTo(n.lastName);
    return 
         (lastCmp!=0 ? lastCmp :
          firstName.compareTo(n.firstName));
}

}

最佳回答:


remove是new出來的對象,hashmap是通過hashcode區分是不是同一個對象的。
兩個對象的hashcode不一樣,除非你重寫一下name類的hashcode獲取方式。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved