java- (c.remove(new Name("f1","l1")));为什么没被移除

作者:用户 来源:互联网 浏览:487 次 时间:2016-05-12 17:55:37

java

java- (c.remove(new Name("f1","l1")));为什么没被移除 - 摘要: (c.remove(newName("f1","l1")));为什么没被移除importjava.util.*;publicclassBasicContaine

问题描述

(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. 重写hashCode, equal方法
  2. 不能直接删除,采用iterator迭代删除
【云栖快讯】诚邀你用自己的技术能力来用心回答每一个问题,通过回答传承技术知识、经验、心得,问答专家期待你加入!  详情请点击
弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率

40+云计算产品,6个月免费体验

现在注册,免费体验40+云产品,及域名优惠!

云服务器9.9元/月,大学必备

热点导航