鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.8.30)
本章内容
1 容器的概念
2 容器API
3 Collection接口
4 Iterator接口
5 增强的for循环
6 Set接口
7 List接口和Comparable接口
8 Collections接口
9 Map接口
10 自动打包/解包
11 泛型(JDK1.5新增)
容器的概念
容器:
java API所提供的一系列类的实例,用于在程序中存放对象
不考虑容器,存储公司人员姓名
// Test.java
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 Test3 {
public static void main(String args[]) {
Name name1 = new Name("f1","l1");
Name name2 = new Name("f2","l2");
Name name3 = new Name("f3","l3");
........................
}
}
关键图
1136 一个图; 一个类;三个知识点;六个接口
容器API
1 j2sdk所提供的容器API位于java.util包内。
2 容器API的类图结构如下图所示:
3 Collection接口-定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。
Set中的数据对象没有顺序且不可重复
List中的数据对象有顺序且可以重复
4 Map接口定义了存储“键(key)--值(value)映射对”的方法(hashCode方法)
Collection接口
Collection接口中所定义的方法
int size()
boolean isEmpty()
boolean contains(Object element)
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()
示例代码:
// Test.java
import java.util.*;
public class Test {
public static void main(String args[]) {
Collection c = new ArrayList();
//可以放入不同类型的对象
c.add("hello");
c.add(new Name("f1", "11"));
c.add(new Integer(100));
System.out.println(c.size());
System.out.println(c);
}
}
class Name {
private String firstName, lastName;
public Name(String s1, String s2) {
this.firstName = s1;
this.lastName = s2;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return firstName + " " + lastName;
}
}