Collection与Map
- 使用Collection收集对象
1.1 Collection架构
Iterator Iterable
Collection
List Set Queue Deque
ArrayList LinkList
HashSet TreeSet
1.2 具有索引的List
示例:
import java.util.*;
import static java.lang.System.out;
public class list {
public static void main(String[] args) {
List names = new ArrayList();
collectName(names);
out.println("访客名单:");
printUpperCase(names);
}
static void collectName(List names){
Scanner console = new Scanner(System.in);
while (true){
out.print(“访客名称");
//nextline()得到Enter键之前的字符,可带空格。
String name = console.nextLine();
if(name.equals("quit")){
break;
}
names.add(name);
}
}
static void printUpperCase(List names){
for(int i =0 ;i<names.size();i++){
String name = (String) names.get(i);
//toUpperCase()方法将小写转换为大写。
out.println(name.toUpperCase());
}
}
}
ArrayList 特性:数组特性,便于查找。
LinkList 特性:链表特性,若经常变动会有很好的效率。
1.3 内容不重复的Set
示例:
import java.util.*;
public class wordcount {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("请输入英文:");
Set words = tokenSet(console.nextLine());
System.out.printf("不重复单字有 %d个: %s%n", words.size(),words);
}
static Set tokenSet(String line){
//String的split()方法指定切割字符串的方式。
String [] tokens = line.split(" “);
//由于Arrays.asList()方法返回List这种Collection,因而传入HashSet(不重复)
return new HashSet(Arrays.asList(tokens));
}
}
HashSet的操作概念是,在内存中开设空间,每个空间会有个哈希编码(Hash Code)。这些空间称为哈希桶(Hash Bucket),如果对象要加入HashSet,则会调用对象的hashCode()取得哈希码,并尝试放入对应的哈希桶中。如果已有对象,则调用equals()比较。重复对象则不予收集。
1.4. 支持队列操作的Queue
Queue定义了自己的offer(),poll(),peek()等方法,失败时会返回特定值。最主要的差别是add(),remove(),element()等方法操作失败时会抛出异常。
示例:
import java.util.*;
interface Request{
void execute();
}
public class RequestQueue {
public static void main(String[] args) {
Queue requests = new LinkedList();
offerRequestTo(requests);
process(requests);
}
static void process(Queue requests) {
while (requests.peek() !=null){
Request request = (Request) requests.poll();
request.execute();
}
}
static void offerRequestTo(Queue requests) {
for(int i = 1;i<6;i++){
Request request = new Request() {
@Override
public void execute() {
System.out.printf("处理数据 %f%n",Math.random()) ;
}
};
requests.offer(request);
}
}
}
结果:
处理数据 0.166687
处理数据 0.884387
处理数据 0.242396
处理数据 0.745725
处理数据 0.013811
1.5 使用泛型
1.6 简介Lambda表达式
1.7. Interable与Iterator
1.8. Comparable与Comparator