Chinaunix首页 | 论坛 | 博客
  • 博客访问: 631728
  • 博文数量: 1008
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 5175
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-31 09:44
文章分类
文章存档

2012年(1008)

我的朋友

分类:

2012-08-01 10:59:56

原文地址:Java Collection接口 作者:luozhiyong131

点击(此处)折叠或打开

  1. import java.util.*;

  2. public class BasicContainer {
  3.     public static void main(String[] args) {
  4.         Collection c = new HashSet();
  5.         c.add("hello");
  6.         c.add(new Name("f1","l1"));
  7.         c.add(new Integer(100));
  8.         c.remove("hello");
  9.         c.remove(new Integer(100));
  10.         System.out.println
  11.                   (c.remove(new Name("f1","l1")));
  12.         System.out.println(c);
  13.     }


  14. }

  15. class Name implements Comparable {
  16.     private String firstName,lastName;
  17.     public Name(String firstName, String lastName) {
  18.         this.firstName = firstName; this.lastName = lastName;
  19.     }
  20.     public String getFirstName() { return firstName; }
  21.     public String getLastName() { return lastName; }
  22.     public String toString() { return firstName + " " + lastName; }
  23.     
  24.     public boolean equals(Object obj) {
  25.      if (obj instanceof Name) {
  26.      Name name = (Name) obj;
  27.      return (firstName.equals(name.firstName))
  28.      && (lastName.equals(name.lastName));
  29.      }
  30.      return super.equals(obj);
  31.     }
  32.         public int hashCode() {
  33.          return firstName.hashCode();
  34.         }
  35.         
  36.         
  37.         
  38.         public int compareTo(Object o) {
  39.         Name n = (Name)o;
  40.         int lastCmp =
  41.             lastName.compareTo(n.lastName);
  42.         return
  43.              (lastCmp!=0 ? lastCmp :
  44.               firstName.compareTo(n.firstName));
  45.     }
  46.         
  47. }
课件: collection.pdf   

阅读(127) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~