GitOPEN's Home.

《Monkey Java》课程9.1之类集框架二

Word count: 456 / Reading time: 2 min
2015/07/27 Share

本节课程将学习以下内容:

  • Collection和Iterator接口
  • Set和HashSet的使用方法
  • Map和HashMap的使用方法

Collection和Iterator接口

关系:

Iterator <– Collection <– Set <– HashSet
Iterator <– Collection <– List <– ArrayList

Collection接口

方法:

boolean add(Object o) 向集合中加入一个对象
void clear() 删除集合当中的所有对象
boolean isEmpty() 判断集合是否为空
remove(Object o)从集合中删除一个对象的引用
int size() 返回集合中元素的数目

Iterator接口

方法:

hsaNext()
next()

Set和HashSet的使用方法

例子1:

新建一个名为Demo01.java的源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Demo01 {
public static void main(String[] args) {

// Set中不允许有重复元素,如果有重复元素,直接忽略
Set<String> set = new HashSet<String>();

set.add("a");
set.add("b");
set.add("c");
set.add("c");
set.add("d");

System.out.println(set.size());

set.remove("a");
System.out.println(set.size());

set.clear();
System.out.println(set.size());

set.add("f");
set.add("g");
set.add("h");
set.add("i");
set.add("j");

System.out.println(set.isEmpty());

// 生成一个迭代器对象,用于遍历整个Set
Iterator<String> it = set.iterator();

while(it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}

Map和HashMap的使用方法

例子2:

新建一个名为Demo02.java的源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

import java.util.HashMap;
import java.util.Map;

public class Demo02 {
public static void main(String[] args) {

Map<String, String> map = new HashMap<String, String>();

map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");

// 如果放进去的键值对的键是存在的,那么后面放入的这个将会覆盖前面的值
map.put("3", "e");

System.out.println(map.size());

String s = map.get("3");
System.out.println(s);

}
}

欣慰帮到你 一杯热咖啡
【奋斗的Coder!】企鹅群
【奋斗的Coder】公众号
CATALOG
  1. 1. Collection和Iterator接口
    1. 1.1. Collection接口
    2. 1.2. Iterator接口
  2. 2. Set和HashSet的使用方法
    1. 2.1. 例子1:
  3. 3. Map和HashMap的使用方法
    1. 3.1. 例子2: