容器:我的java笔记(2)

关于容器的remove方法:

有一个例子:
当remove中的对象和列表中的对象Equals函数为true时,
才会将列表中对象删除掉。 注意:如果一个对象没有重写equals函数
将会调用父类的equals函数 ,判断是否两个对象是否为同一个对象引用。

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));
    }
       
}
 

你可能感兴趣的:(java,基础,职场,休闲)