Collection中的remove和contains方法,都是挨个比较每个对象是否equals参数中的对象,如果equals了,就remove掉或者包含。
看下面例子:
package com.cy.container; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; public class BasicContainer { public static void main(String[] args) { Collection c = new ArrayList(); 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{ private String firstName, lastName; public Name(String firstName, String lastName) { super(); this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } @Override public String toString() { return "Name [firstName=" + firstName + ", lastName=" + lastName + "]"; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Name other = (Name) obj; if (firstName == null) { if (other.firstName != null) return false; } else if (!firstName.equals(other.firstName)) return false; if (lastName == null) { if (other.lastName != null) return false; } else if (!lastName.equals(other.lastName)) return false; return true; } }