本章内容
容器的概念
容器 API
Collection 接口
Iterator 接口
增强的for循环
Set 接口
List 接口 和 Comparable 接口
Collections类
Map 接口
自动打包/解包
泛型(JDK1.5新增)
容器的概念
阅读如下程序:
public class Name {
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 class Test {
public static void main(String arg[]) {
Name name1 = new Name("f1","l1");
Name name2 = new Name("f2","l2");
Name name3 = new Name("f3","l3");
… … …
}
}
容器:
Java API 所提供的一系列类的实例,用于在程序中存放对象。
★Collection 接口-定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。
Set 中的数据对象没有顺序且不可以重复。
List 中的数据对象有顺序且可以重复。(即互相equals)
★Map 接口定义了存储“键(key)- 值(value)映射对”的方法。
Collection 接口
Collection接口中所定义的方法:int size();
boolean isEmpty(); //里面是不是空的
void clear(); //清空
boolean contains(Object element); //equals 等于 contain 包含
boolean add(Object element); //添加某个元素
boolean remove(Object element); //
Iterator iterator();
boolean containsAll(Collection c);
boolean addAll(Collection c);
boolean removeAll(Collection c);
boolean retainAll(Collection c); //求交集
Object[] toArray(); //返回包含此 collection 中所有元素的数组。
Collection 方法举例
import java.util.*;
public class Test {
public static void main(String[] args) {
Collection c = new ArrayList();
//可以放入不同类型的对象
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
System.out.println(c.size());
System.out.println(c);
}
}
输出结果:
3
[hello, f1 l1, 100]
BasicContainer.java 例子
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);
}
/**
* 输出结果为:
* false
* [f1l1]
*/
}
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));
}
}