Java之集合

面向对象语言对事物的体现都是以对象的形式,所以为了方便对多 个对象的操作,就对对象进行存储,集合就是存储对象常用的一 种方式

集合的概念

数组和集合的区别

  • 数组虽然也可以存储对象,但长度是固定的,集合长度是可变的
  • 数组中可以存储基本数据类型,集合只能存储对象

集合类的特点

集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象

集合类的关系图

Collection集合

集合中存储的都是对象的引用(地址)

Collection框架的共性功能

  • 添加
    1
    2
    add(e);
    addAll(collection);

add方法的参数类型是Object,以便于接收任意类型对象

  • 删除

    1
    2
    3
    remove(e);
    removeAll(collection);
    clear();
  • 判断。

    1
    2
    contains(e);
    isEmpty();
  • 获取

    1
    2
    iterator();
    size();
  • 获取交集

    1
    obj1.retainAll(obj2);
  • 去除重复

    1
    obj1.removeAll(obj2);
  • 集合变数组

    1
    toArray();

Collection接口的常用子类

Collection接口有两个子接口:List(列表),Set(集)

  • List:可存放重复元素,元素存取是有序的(存在索引)
  • Set:不可以存放重复元素,元素存取是无序的

迭代

迭代的使用

  • 迭代是取出集合中元素的一种方式
  • 因为Collection中有iterator方法,所以每一个子类集合对象都具备迭代器
  • 迭代器是取出方式,会直接访问集合中的元素,所以将迭代器通过内部类的形式来进行描述,通过容器的iterator()方法获取该内部类的对象

用法:

1
2
3
4
Iterator iter = l.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}

1
2
3
for(Iterator iter = iterator(); iter.hasNext();  ) {
System.out.println(iter.next());
}

迭代注意事项

  • 迭代器在Collcection接口中是通用的,它替代了Vector类中的Enumeration(枚举)
  • 迭代器的next方法是自动向下取元素,要避免出现NoSuchElementException
  • 迭代器的next方法返回值类型是Object,所以要记得类型转换

List接口

List接口的常用子类

  • Vector:数组结构,线程同步,线程安全,但速度慢,已被ArrayList替代
  • ArrayList:数组结构,线程不同步,线程不安全,查询速度快
  • LinkedList:链表结构,增删速度快

取出LIst集合中元素的方式:

  • get(int index):通过脚标获取元素
  • iterator():通过迭代方法获取迭代器对象

List特有方法

凡是可以操作角标的方法都是该体系特有的方法

List特有常用方法

  • 1
    2
    add(index, element);
    addAll(index, Collection);
  • 1
    remove(index);
  • 1
    set(index,element);
  • 1
    2
    3
    4
    5
    6
    get(index):
    indexOf(o);
    subList(from, to);
    listIterator();
    int indexOf(obj);//获取指定元素的位置。
    ListIterator listIterator();

List使用注意事项

  • List集合特有的迭代器。ListIterator是Iterator的子接口
  • 在迭代时,不可以通过集合对象的方法操作集合中的元素,因为会发生ConcurrentModificationException异常
  • 在迭代时,只能用迭代器的方式操作元素,可是Iterator方法是有限的,只能对元素进行判断,取出,删除的操作,如果想要其他的操作如添加,修改等,就需要使用其子接口:ListIterator,该接口只能通过List集合的listIterator方法获取

Vector类

枚举就是Vector特有的取出方式,发现枚举和迭代器很像,其实枚举和迭代是一样的
因为枚举的名称以及方法的名称都过长,所以被迭代器取代了

1
2
3
4
5
6
7
8
9
10
11
12
13
class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
v.add("java01");
v.add("java02");
v.add("java03");
v.add("java04");
Enumeration en = v.elements();
while(en.hasMoreElements()) {
System.out.println(en.nextElement());
}
}
}

LinkedList类

LinkedList:特有方法

1
2
3
4
5
6
addFirst();
addLast();
getFirst();
getLast(); //获取元素,但不删除元素。如果集合中没有元素,会出现NoSuchElementException
removeFirst();
removeLast(); //获取元素,但是元素被删除。如果集合中没有元素,会出现NoSuchElementException

从JDK1.6出现了替代方法

1
2
3
4
5
6
offerFirst();
offerLast();
peekFirst();
peekLast(); //获取元素,但不删除元素。如果集合中没有元素,会返回null
pollFirst();
pollLast(); //获取元素,但是元素被删除。如果集合中没有元素,会返回null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class LinkedListDemo {
public static void main(String[] args) {
LinkedList link = new LinkedList();
link.addLast("java01");
link.addLast("java02");
link.addLast("java03");
link.addLast("java04");
System.out.println(link);
while(!link.isEmpty())
{
System.out.println(link.removeLast());
}
}
}

使用LinkedList模拟一个堆栈或者队列数据结构

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
import java.util.*;
class MyQueue {
private LinkedList link;
MyQueue() {
link = new LinkedList();
}
public void myAdd(Object obj) {
link.addFirst(obj);
}
public Object myGet() {
return link.removeFirst();
}
public boolean isNull() {
return link.isEmpty();
}

}

class LinkedListTest {
public static void main(String[] args) {
MyQueue mq = new MyQueue();
mq.myAdd("java01");
mq.myAdd("java02");
mq.myAdd("java03");
mq.myAdd("java04");
while(!mq.isNull()) {
System.out.println(mq.myGet());
}
}
}

ArrayList类

例子:存人对象,同姓名同年龄,视为同一个人

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
43
44
45
46
47
48
49
class Person {
private String name;
private int age;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setAge(int age){
this.age = age;
}

public int getAge(){
return age;
}

Person(String name, int age) {
this.name = name;
this.age = age;
}

public boolean equals(Object obj) {
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
}

class ArrayListDemo {

public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Person("lisi01",30));
al.add(new Person("lisi02",32));
al.add(new Person("lisi02",32));
al.add(new Person("lisi03",33));

Iterator it = al.iterator();
while(it.hasNext()) {
Person p = (Person)it.next();
System.out.println(p.getName() + "::" + p.getAge());
}
}
}

去除重复元素

1
2
3
4
5
6
7
8
9
10
11
12
public static ArrayList singleElement(ArrayList al) {
//定义一个临时容器。
ArrayList newAl = new ArrayList();

Iterator it = al.iterator();
while(it.hasNext()) {
Object obj = it.next();
if(!newAl.contains(obj))
newAl.add(obj);
}
return newAl;
}

Set接口

Set接口中常用的类

  • HashSet:哈希表结构,线程不安全,存取速度快
  • TreeSet:二叉树结构,线程不安全,可以对Set集合中的元素进行排序

Set集合元素唯一性原因

  • HashSet:通过equals方法和hashCode方法来保证元素的唯一性
  • TreeSet:通过compareTo或者compare方法中的来保证元素的唯一性。元素是以二叉树的形式存放的

HashSet类

  • 在HashSet中不能有重复
    如果元素的HashCode值相同,才会判断equals是否为true
    如果元素的hashcode值不同,不会调用equals
    对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法
  • 存入成功返回true,存入失败返回false
  • 使用迭代器取出,其元素输出是无序的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.*;
class HashSetDemo {
public static void main(String[] args) {
HashSet hs = new HashSet();

System.out.println(hs.add("java01")); //true
System.out.println(hs.add("java01")); //false
hs.add("java02");
hs.add("java03");
hs.add("java04");

Iterator it = hs.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}

通过姓名和年龄判断是否是同一个人

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.*;

/*
往hashSet集合中存入自定对象
姓名和年龄相同为同一个人,重复元素。
*/
class Person {
private String name;
private int age;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setAge(int age){
this.age = age;
}

public int getAge(){
return age;
}

Person(String name,int age) {
this.name = name;
this.age = age;
}

public int hashCode() {
//System.out.println(this.name+"....hashCode");
return name.hashCode() + age * 60; //防止哈希值重复
}

public boolean equals(Object obj) {
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
//System.out.println(this.name+"...equals.."+p.name);
return this.name.equals(p.name) && this.age == p.age;
}
}

class HashSetTest {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add(new Person("a1",11));
hs.add(new Person("a2",12));
hs.add(new Person("a3",13));
hs.add(new Person("a2",12));
hs.add(new Person("a4",14));
Iterator it = hs.iterator();
while(it.hasNext()) {
Person p = (Person)it.next();
System.out.println(p.getName() + "::" + p.getAge());
}
}
}

TreeSet类

保证元素唯一性的依据:compareTo方法的返回值为零,代表相同元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;
class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add("abc");
ts.add("abd");
ts.add("cba");
ts.add("aaa");
Iterator it = ts.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}

  • 实现正序输出
    实现compareTo接口,复写compare方法返回正数
  • 实现反转输出
    实现compareTo接口,复写compare方法返回负数

  • TreeSet排序的第一种方式:
    让元素自身具备比较性
    元素需要实现Comparable接口,覆盖compareTo方法
    也种方式也成为元素的自然顺序,或者叫做默认顺序

    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
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    import java.util.*;
    /*
    需求:
    往TreeSet集合中存储自定义对象学生
    想按照学生的年龄进行排序
    */

    class TreeSetDemo {
    public static void main(String[] args) {
    TreeSet ts = new TreeSet();
    ts.add(new Student("lisi02",22));
    ts.add(new Student("lisi007",20));
    ts.add(new Student("lisi09",19));
    ts.add(new Student("lisi08",19));
    //ts.add(new Student("lisi007",20));
    //ts.add(new Student("lisi01",40));
    Iterator it = ts.iterator();
    while(it.hasNext()) {
    Student stu = (Student)it.next();
    System.out.println(stu.getName() + "..." + stu.getAge());
    }
    }
    }

    class Student implements Comparable { //该接口强制让学生具备比较性
    private String name;
    private int age;

    public void setName(String name){
    this.name = name;
    }

    public String getName(){
    return name;
    }

    public void setAge(int age){
    this.age = age;
    }

    public int getAge(){
    return age;
    }

    Student(String name,int age) {
    this.name = name;
    this.age = age;
    }

    public int compareTo(Object obj) {
    if(!(obj instanceof Student))
    throw new RuntimeException("不是学生对象");
    Student s = (Student)obj;
    if(this.age > s.age)
    return 1;
    if(this.age == s.age) {
    return this.name.compareTo(s.name);
    }
    return -1;
    }
    }
  • TreeSet的第二种排序方式
    当元素自身不具备比较性时,或者具备的比较性不是所需要的
    这时就需要让集合自身具备比较性
    在集合初始化时,就有了比较方式
    将比较器对象作为参数传递给TreeSet集合的构造函数

    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
    import java.util.*;
    /*
    按照字符串长度排序
    */
    class TreeSetTest {
    public static void main(String[] args) {
    TreeSet ts = new TreeSet(new StrLenComparator());
    ts.add("abcd");
    ts.add("cc");
    ts.add("cba");
    ts.add("aaa");
    ts.add("z");
    Iterator it = ts.iterator();
    while(it.hasNext()) {
    System.out.println(it.next());
    }
    }
    }

    class StrLenComparator implements Comparator {
    public int compare(Object o1,Object o2) {
    String s1 = (String)o1;
    String s2 = (String)o2;
    int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
    if(num == 0)
    return s1.compareTo(s2);
    return num;
    }
    }

Map集合

该集合存储键值对。一对一对往里存。而且要保证键的唯一性

Map与Collection不同

  • Map与Collection在集合框架中属并列存在
  • Map存储的是键值对
  • Map存储元素使用put方法,Collection使用add方法
  • Map集合没有直接取出元素的方法,而是先转成 Set集合,在通过迭代获取元素
  • Map集合中键要保证唯一性

Map集合的常用子类

  • Hashtable:哈希表结构,线程同步,线程安全,速度慢,不允许存放null键,null值,已被HashMap替代
  • HashMap:哈希表结构,线程不同步,线程不安全,速度快,允许存放null键,null值
  • TreeMap:二叉树结构,线程不同步,对键进行排序,排序原理与TreeSet相同

Map集合常用方法

  • 添加

    1
    2
    put(K key, V value) //如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值,并返回被覆盖的值
    putAll(Map<? extends K,? extends V> m)
  • 删除

    1
    2
    clear()
    remove(Object key)
  • 判断

    1
    2
    3
    containsValue(Object value)
    containsKey(Object key)
    isEmpty()
  • 获取

    1
    2
    3
    4
    5
    get(Object key)
    size()
    values()
    entrySet()
    keySet()

Map集合取值的方法

  • Set
    keySet:将map中所有的键存入到Set集合。因为set具备迭代器
    所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值
    Map集合的取出原理:将map集合转成set集合。在通过迭代器取出

    1
    2
    3
    4
    5
    6
    7
    Set<String> keySet = map.keySet();
    Iterator<String> it = keySet.iterator();
    while(it.hasNext()) {
    String key = it.next();
    String value = map.get(key);
    System.out.println("key:" + key + ",value:" + value);
    }
  • Set<Map.Entry<k,v>>
    entrySet:将map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry
    Entry其实就是Map中的一个static内部接口
    public static interface Man.Entry<K,V>
    为什么要定义在内部呢?
    因为只有有了Map集合,有了键值对,才会有键值的映射关系。关系属于Map集合中的一个内部事物,而且该事物在直接访问Map集合中的元素

    1
    2
    3
    4
    5
    6
    7
    8
    Set<Map.Entry<String, String>> entrySet = map.entrySet();
    Iterator<Map.Entry<String, String>> it = entrySet.iterator();
    while(it.hasNext()) {
    Map.Entry<String, String> me = it.next();
    tring key = me.getKey();
    String value = me.getValue();
    System.out.println(key + ":" + value);
    }

HashMap类

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
每一个学生都有对应的归属地
学生Student,地址String
学生属性:姓名,年龄
注意:姓名和年龄相同的视为同一个学生,保证学生的唯一性
*/
import java.util.*;
class Student implements Comparable<Student> {
private String name;
private int age;

Student(String name, int age) {
this.name = name;
this.age = age;
}

public int compareTo(Student s) {
int num = new Integer(this.age).compareTo(new Integer(s.age));
if(num == 0)
return this.name.compareTo(s.name);
return num;
}

public int hashCode() {
return name.hashCode() + age * 34;
}

public boolean equals(Object obj) {
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");

Student s = (Student)obj;
return this.name.equals(s.name) && this.age == s.age;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String toString() {
return name + ":" + age;
}
}

class Test {
public static void main(String[] args) {
HashMap<Student,String> hm = new HashMap<Student,String>();

hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi1",21),"tianjin");
hm.put(new Student("lisi2",22),"shanghai");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");

//第一种取出方式 keySet
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext()) {
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(stu + "..." + addr);
}

//第二种取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
while(iter.hasNext()) {
Map.Entry<Student,String> me = iter.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu + "..." + addr);
}
}
}

TreeMap类

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
/*
需求:对学生对象的年龄进行升序排序
因为数据是以键值对形式存在的
所以要使用可以排序的Map集合。TreeMap
*/
import java.util.*;

class StuNameComparator implements Comparator<Student> {
public int compare(Student s1,Student s2) {
int num = s1.getName().compareTo(s2.getName());
if(num == 0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}

class Test {
public static void main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());

tm.put(new Student("blisi3",23),"nanjing");
tm.put(new Student("lisi1",21),"beijing");
tm.put(new Student("alisi4",24),"wuhan");
tm.put(new Student("lisi1",21),"tianjin");
tm.put(new Student("lisi2",22),"shanghai");

Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
while(it.hasNext()) {
Map.Entry<Student,String> me = it.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu + "::" + addr);
}
}
}

集合框架中的工具类

Collections

  • 对集合进行查找
  • 取出集合中的大值,小值
  • 对List集合进行排序
    TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder(new StrLenComparator()));

Arrays

  • 将数组转成List集合
  • 对数组进行排序
  • 对数组进行二分查找

让不安全集合转为安全集合

synchronizedCollection(Collection<T> c)
synchronizedList(List<T> list)
synchronizedMap(Map<K,V> m)
synchronizedSet(Set<T> s)

新增for语句

Collection在JDK1.5后出现的父接口Iterable就是提供了这个for语句
格式:

1
2
3
for(数据类型 变量名 : 数组或集合) {
执行语句;
}

简化了对数组,集合的遍历
对集合进行遍历,只能获取集合元素。但是不能对集合进行操作
迭代器除了遍历,还可以进行remove集合中元素的动作
如果是用ListIterator,还可以在遍历过程中对集合进行增删改查的动作

1
2
3
4
5
6
7
8
9
10
11
12
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"a");
hm.put(2,"b");
hm.put(3,"c");
Set<Integer> keySet = hm.keySet();
for(Integer i : keySet) {
System.out.println(i+"::"+hm.get(i));
}

for(Map.Entry<Integer,String> me : hm.entrySet()) {
System.out.println(me.getKey()+"------"+me.getValue());
}

可变参数

从1.5开始,java支持可变参数
在此之前,可以通过数组传递多个相同参数

1
2
3
4
5
6
7
8
9
class Test {
public static void main(String[] args) {
int[] arr = {3,4};
show(arr);
}
public static void show(int[] arr) {
···
}
}

可变参数:其实就是上一种数组参数的简写形式,不用每一次都手动的建立数组对象, 只要将要操作的元素作为参数传递即可,隐式将这些参数封装成了数组
可变参数一定要定义在参数列表最后面

1
2
3
4
5
6
7
8
class Test {
public static void main(String[] args) {
show("test", 4, 5);
}
public static void show(String str,int... arr) {
System.out.println(arr.length);
}
}

Donate comment here