Java中的集合详解及代码测试

1:对象数组
(1)数组既可以存储基本数据类型,也可以存储引用类型。它存储引用类型的时候的数组就叫对象数组。

2:集合(Collection)
(1)集合的由来
我们学习的是Java -- 面向对象 -- 操作很多对象 -- 存储 -- 容器(数组和StringBuffer) -- 数组
而数组的长度固定,所以不适合做变化的需求,Java就提供了集合供我们使用。


(2)集合和数组的区别
A:长度区别
          数组固定
          集合可变
B:内容区别
         数组可以是基本类型,也可以是引用类型
         集合只能是引用类型
C:元素内容
        数组只能存储同一种类型
        集合可以存储不同类型(其实集合一般存储的也是同一种类型)


(3)集合的继承体系结构

由于需求不同,Java就提供了不同的集合类。这多个集合类的数据结构不同,但是它们都是要提供存储和遍历功能的,
我们把它们的共性不断的向上提取,最终就形成了集合的继承体系结构图。

Collection
     |--List
         |--ArrayList
         |--Vector
         |--LinkedList
   |--Set
        |--HashSet
        |--TreeSet


(4)Collection的功能概述
A:添加功能

boolean add(E e)添加一个元素
boolean addAll(Collection<? extends E> c)添加一个集合的元素


B:删除功能

void clear()移除所有元素
boolean remove(Object o)移除一个元素
boolean removeAll(Collection<?> c)移除一个集合的元素


C:判断功能

boolean contains(Object o)如果此 collection 包含指定的元素,则返回 true
boolean containsAll(Collection<?> c)如果此 collection 包含指定 collection 中的所有元素,则返回 true。 
boolean isEmpty()如果此 collection 不包含元素,则返回 true


D:获取功能

Iterator<E> iterator()返回在此 collection 的元素上进行迭代的迭代器


E:长度功能

int size()返回此 collection 中的元素数


F:交集(了解)

boolean retainAll(Collection<?> c)仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。


G:把集合转数组(了解)

<T> T[] toArray(T[] a)返回包含此 collection 中所有元素的数组

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 
 4 public class CollectioonDemo {
 5     public static void main(String[] args) {
 6         //创建对象
 7         Collection c1 = new ArrayList();
 8         
 9         //添加元素
10         c1.add("abc1");
11         c1.add("abc2");
12         c1.add("abc3");
13         c1.add("abc4");
14         
15         Collection c2 = new ArrayList();
16         c1.add("abc4");
17         c2.add("abc5");
18         c2.add("abc6");
19         c2.add("abc7");
20         
21         //c1.clear();//移除所有元素
22         //System.out.println("remove:" + c1.remove("abc1"));//remove:true
23         //System.out.println("remove:" + c1.remove("abc"));//remove:false
24         
25         //判断集合中是否包含指定元素
26         //System.out.println("contains:" + c1.contains("abc2"));//contains:true
27         //System.out.println("contains:" + c1.contains("abc"));//contains:false
28         
29         //判断是否为空
30         //System.out.println("isEmpty:" + c1.isEmpty());//isEmpty:false
31         
32         //元素个数
33         //System.out.println("size:" + c1.size());//size:5
34         
35         //添加一个集合的元素
36         //System.out.println("addAll:" + c1.addAll(c2));//addAll:true
37         //System.out.println("c1:" + c1);//c1:[abc1, abc2, abc3, abc4, abc4, abc5, abc6, abc7]
38         
39         //移除一个集合的元素   只用有一个元素被移除了就返回true
40         //System.out.println("removeAll:" + c1.removeAll(c2));
41         
42         //只有包含所有的元素才叫包含
43         //System.out.println("containsAll:" + c1.containsAll(c2));
44         
45         //交集   
46         /*
47          * A对B做交集,最终的结果保存在A中,B不变
48          * 返回值表示A是否发生过变化
49          */
50         System.out.println("retainAll:" + c1.retainAll(c2));
51         System.out.println("c1:" + c1);
52         System.out.println("c2:" + c2);
53         
54     }
55 
56 }


(5)Collection集合的遍历
A:把集合转数组(了解)

实例1

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 
 4 public class CollectioonDemo2 {
 5     //集合变数组   实现集合的遍历
 6     public static void main(String[] args) {
 7         Collection c = new ArrayList();
 8         
 9         c.add("hello");//Object obj = "hello" 向上转型
10         c.add("world");
11         c.add("java");
12         
13         //集合c转数组
14          Object[] objs = c.toArray();
15          for(int x = 0;x < objs.length;x++){
16              System.out.println(objs[x]);
17             //object没有length()方法,必须将元素还原成字符串;向下转型
18              String s = (String) objs[x];
19              System.out.println(s+ "-----"+s.length());
20          } 
21     }
22     
23     /*
24      *     hello
25         hello-----5
26         world
27         world-----5
28         java
29         java-----4
30 
31      */
32 
33 }

实例2

 1 public class Student {
 2     private String name;
 3     
 4     private int age;
 5 
 6     public Student() {
 7         super();
 8         // TODO Auto-generated constructor stub
 9     }
10 
11     public Student(String name, int age) {
12         super();
13         this.name = name;
14         this.age = age;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32      
33 }
 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 
 4 public class StudentDemo {
 5     public static void main(String[] args) {
 6         //创建集合对象
 7         Collection c = new ArrayList();
 8         
 9         //创建学生对象
10         Student s1 = new Student("张三", 23);
11         Student s2 = new Student("李四", 25);
12         Student s3 = new Student("王五", 26);
13         
14         //将学生对象添加到集合
15         c.add(s1);
16         c.add(s2);
17         c.add(s3);
18         
19         //集合转化为数组
20         Object[] obj = c.toArray();
21         
22         //遍历数组
23         for(int i = 0; i < obj.length; i++){
24             Student s = (Student)obj[i];
25             System.out.println(s.getName() + "-------" + s.getAge());
26         }
27         
28     }
29 
30 }


B:迭代器(集合专用方式)

实例1

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 
 5 public class IteratorDemo {
 6     public static void main(String[] args) {
 7         
 8         Collection c = new ArrayList();
 9 
10         c.add("java");
11         c.add("hello");
12         c.add("word");
13         c.add("hi");
14 
15         Iterator it = c.iterator();
16         while (it.hasNext()){
17             String s = (String)it.next();
18             System.out.println(s);
19         }
20         
21         
22     }
23 
24 }

实例2

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 
 5 public class ColectionTest {
 6     public static void main(String[] args) {
 7         
 8         Collection c = new ArrayList();
 9         
10         Student s1 = new Student("貂蝉",25);
11         Student s2 = new Student("小乔",16);
12         Student s3 = new Student("黄月英",20);
13         Student s4 = new Student();
14         s4.setName("大桥");
15         s4.setAge(26);
16         
17         
18         c.add(s1);
19         c.add(s2);
20         c.add(s3);
21         c.add(s4);
22         c.add(new Student("孙尚香",18));//匿名对象
23         
24         Iterator it = c.iterator();
25         while (it.hasNext()){
26             Student s = (Student)it.next();
27             System.out.println(s.getName() + "---" + s.getAge());
28         }
29         
30         
31     }
32 
33 }
 1 public class Student {
 2     private String name;
 3     
 4     private int age;
 5 
 6     public Student() {
 7         super();
 8         // TODO Auto-generated constructor stub
 9     }
10 
11     public Student(String name, int age) {
12         super();
13         this.name = name;
14         this.age = age;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public int getAge() {
26         return age;
27     }
28 
29     public void setAge(int age) {
30         this.age = age;
31     }
32 
33     @Override
34     public String toString() {
35         
36         return "Student [name = " + name + ", age = " + age +" ]";
37     }
38     
39      
40 }


(6)迭代器
A:是集合的获取元素的方式。
B:是依赖于集合而存在的。
C:迭代器的原理和源码。
a:为什么定义为了一个接口而不是实现类?
b:看了看迭代器的内部类实现。


(7)Collection集合的案例(遍历方式 迭代器)
集合的操作步骤:
A:创建集合对象
B:创建元素对象
C:把元素添加到集合
D:遍历集合

A:存储字符串并遍历

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 
 5 /*
 6  * 存储字符串并遍历
 7  * 步骤:
 8  *    1.创建集合对象
 9  *    2.创建字符串对象
10  *    3.把字符串对象添加到集合
11  *    4.遍历集合
12  */
13 public class CollectionTest {
14     public static void main(String[] args) {
15         //1.创建集合对象
16         Collection c = new ArrayList(); 
17         /*
18          * 创建字符串对象
19          * 把字符串对象添加到集合
20          */
21         c.add("张三");
22         c.add("李四");
23         c.add("王五");
24         c.add("刘二");
25         //通过迭代器遍历集合
26         Iterator it = c.iterator();
27         //通过迭代器对象的hashNext()方法判断有没有元素
28         while(it.hasNext()){
29             //通过迭代器对象的next()方法获取元素
30             String s = (String) it.next();
31             System.out.println(s);
32         }
33     }
34 
35 }


B:存储自定义对象并遍历

 1 import java.util.ArrayList;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 
 5 /*
 6  * 存储自定义对象并遍历(Student name age)
 7  * 步骤:
 8  *       1.创建学生类    
 9  *    2.创建集合对象
10  *    3.创建学生对象
11  *    3.把学生对象添加到集合
12  *    4.遍历集合
13  */
14 public class CollectionTest {
15     public static void main(String[] args) {
16         //创建集合对象
17         Collection c = new ArrayList(); 
18 
19         //创建学生对象
20         Student s1 = new Student("张三", 23);
21         Student s2 = new Student("李四", 21);
22         Student s3 = new Student("王五", 12);
23         //通过getset方法赋值
24         Student s4 = new Student();
25         s4.setName("刘二");
26         s4.setAge(22);
27         
28         //把学生对象添加到集合
29         c.add(s1);
30         c.add(s2);
31         c.add(s3);
32         c.add(s4);
33         c.add(new Student("小儿", 10));//匿名对象
34         
35         //通过迭代器遍历集合
36         Iterator it = c.iterator();
37         //通过迭代器对象的hashNext()方法判断有没有元素
38         while(it.hasNext()){
39             //通过迭代器对象的next()方法获取元素
40             Student s = (Student) it.next();
41             System.out.println(s.getName()+ "-----" + s.getAge());
42         }
43     }
44 
45 }
 1 public class Student {
 2     private String name;
 3     private int age;
 4 
 5     public Student() {
 6         super();
 7         // TODO Auto-generated constructor stub
 8     }
 9 
10 
11     public Student(String name, int age) {
12         super();
13         this.name = name;
14         this.age = age;
15     }
16 
17 
18     public String getName() {
19         return name;
20     }
21 
22 
23     public void setName(String name) {
24         this.name = name;
25     }
26 
27 
28     public int getAge() {
29         return age;
30     }
31 
32 
33     public void setAge(int age) {
34         this.age = age;
35     }
36     
37 }

3:集合(List)
(1)List是Collection的子接口
特点:有序(存储顺序和取出顺序一致),可重复。

存储字符串并遍历:

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 
 5 //List集合存储字符串并遍历
 6 public class ListDemo {
 7     public static void main(String[] args) {
 8         //创建集合对象
 9         List list = new ArrayList();
10         
11         //创建字符串并添加到集合
12         list.add("hello");
13         list.add("world");
14         list.add("java");
15         
16         //遍历集合
17         Iterator it = list.iterator();
18         while(it.hasNext()){
19             String s = (String) it.next();
20             System.out.println(s);
21         }
22     }
23 
24 }

测试有序可重复:

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 
 5 /*
 6  * List集合特点:有序(存储和取出的元素一直),可重复的
 7  */
 8 public class ListDemo {
 9     public static void main(String[] args) {
10         //创建集合对象
11         List list = new ArrayList();
12         
13         //创建字符串并添加到集合
14         list.add("hello");
15         list.add("world");
16         list.add("java");
17         list.add("java");
18         list.add("Linux");
19         list.add("java");
20         list.add("Linux");
21         
22         //遍历集合
23         Iterator it = list.iterator();
24         while(it.hasNext()){
25             String s = (String) it.next();
26             System.out.println(s);
27             /*
28              *     hello
29                 world
30                 java
31                 java
32                 Linux
33                 java
34                 Linux
35              */
36         }
37     }
38 
39 }

存储自定义对象并遍历:

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 
 5 /*
 6  * 存储自定义对象并遍历
 7  */
 8 public class ListDemo {
 9     public static void main(String[] args) {
10         //创建集合对象
11         List list = new ArrayList();
12         
13         //创建学生对象
14         Student s1 = new Student("张三", 23);
15         Student s2 = new Student("李四", 20);
16         Student s3 = new Student("王五", 24);
17         
18         //将学生对象添加到集合
19         list.add(s1);
20         list.add(s2);
21         list.add(s3);
22         
23         //遍历集合
24         Iterator it = list.iterator();
25         while(it.hasNext()){
26             Student s = (Student) it.next();
27             System.out.println(s.getName() + "-------" + s.getAge());
28         }
29     }
30 
31 }
 1 public class Student {
 2     private String name;
 3     private int age;
 4 
 5     public Student() {
 6         super();
 7         // TODO Auto-generated constructor stub
 8     }
 9 
10 
11     public Student(String name, int age) {
12         super();
13         this.name = name;
14         this.age = age;
15     }
16 
17 
18     public String getName() {
19         return name;
20     }
21 
22 
23     public void setName(String name) {
24         this.name = name;
25     }
26 
27 
28     public int getAge() {
29         return age;
30     }
31 
32 
33     public void setAge(int age) {
34         this.age = age;
35     }
36     
37 }


(2)List的特有功能
A:添加功能

    void add(int index, Object element):在指定位置添加元素
B:删除功能

   Object remove(int index):根据索引删除元素,返回被删除的元素
C:获取功能

   Object get (int index):获取指定位置的元素
D:列表迭代器功能

     ListItertor listIterator():list集合特有的迭代器
E:修改功能

 Object set (int index,Object element):根据索引修改元素,返回被修改的元素

 1 public class ListDemo2 {
 2 
 3     public static void main(String[] args) {
 4         //创建集合对象
 5         List list = new ArrayList();
 6         
 7         //添加元素
 8         list.add("hello");
 9         list.add("world");
10         list.add("java");
11         
12         //System.out.println("list:" + list);
13         /*
14          * list:[hello, world, java]
15          */
16         
17         //添加功能
18         //list.add(1, "linux");
19         //System.out.println("list:" + list);
20         /*
21          * list:[hello, linux, world, java]
22          */
23         //获取功能
24         //System.out.println("get:" + list.get(2));
25         //get:java
26         
27         //删除功能
28         //System.out.println("remove:" + list.remove(1));
29         //remove:world
30         
31         //修改功能
32         System.out.println("set:" + list.set(1, "javaee"));
33         System.out.println("list:" + list);
34         /*
35          * set:world
36            list:[hello, javaee, java]
37          */
38         
39     }
40 }


(3)List集合的特有遍历功能
A:由size()和get()结合。
B:代码演示

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class ListDemo1 {
 5     public static void main(String[] args) {
 6         //创建集合对象
 7         List list  = new ArrayList();
 8         
 9         //集合中添加元素
10         list.add("hello");
11         list.add("world");
12         list.add("java");
13         
14         //遍历输出   list集合的特有遍历size()和get()结合
15         for(int x = 0; x < list.size(); x++){
16             String s = (String) list.get(x);
17             System.out.println(s);
18         }
19     }
20 }

自定义学生对象,两种遍历方式(迭代器和普通for)

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 
 5 /*
 6  * 存储自定义对象,使用普通for 循环(get()size()方法结合)
 7  */
 8 public class ListDemo1 {
 9     public static void main(String[] args) {
10         //创建集合对象
11         List list  = new ArrayList();
12         
13         //创建学生对象
14         Student s1 = new Student("张三", 12);
15         Student s2 = new Student("李四", 11);
16         Student s3 = new Student("王五", 20);
17         
18         //学生对象添加到集合
19         list.add(s1);
20         list.add(s2);
21         list.add(s3);
22         
23         //迭代器遍历
24         Iterator it = list.iterator();
25         while(it.hasNext()){
26             Student s = (Student) it.next();
27             System.out.println(s.getName() + "----" + s.getAge());
28         }
29         System.out.println("-----------");
30         //遍历输出   list集合的特有遍历size()和get()结合
31         for(int x = 0; x < list.size(); x++){
32             Student s = (Student) list.get(x);
33             System.out.println(s.getName() + "----" + s.getAge());
34         }
35     }
36 }


(4)列表迭代器的特有功能;(了解)
可以逆向遍历,但是要先正向遍历,所以无意义,基本不使用。


(5)并发修改异常
A:出现的现象
迭代器遍历集合,集合修改集合元素
B:原因
迭代器是依赖于集合的,而集合的改变迭代器并不知道。
C:解决方案
a:迭代器遍历,迭代器修改(ListIterator)
元素添加在刚才迭代的位置
b:集合遍历,集合修改(size()和get())
元素添加在集合的末尾

 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 import java.util.List;
 4 import java.util.ListIterator;
 5 
 6 public class ListDemo2 {
 7 
 8     public static void main(String[] args) {
 9         //创建List集合对象
10         List list = new ArrayList();
11         
12         //添加元素
13         list.add("hello");
14         list.add("world");
15         list.add("java");
16         
17     
18         //迭代器遍历
19 //        Iterator it = list.iterator();
20 //        while(it.hasNext()){
21 //            String s = (String) it.next();
22 //            if("world".equals(s)){
23 //                list.add("javaee");
24 //            }
25 //        }
26         /*
27          * ConcurrentModificationException
28          */
29 
30         //1.迭代器遍历元素,迭代器修改元素
31         //Iterator迭代器没有添加功能,使用它的子接口ListIterator
32         ListIterator lit = list.listIterator();
33         while(lit.hasNext()){
34             String s = (String)lit.next();
35             if("world".equals(s)){
36                 list.add("javaee");
37             }
38         }//list:[hello, world,javaee, java]
39         
40         //2.集合遍历元素,集合修改元素(普通for)
41 //        for(int x = 0; x < list.size(); x++){
42 //            String s = (String) list.get(x);
43 //            if("world".equals(s)){
44 //                list.add("javaee");
45 //            }
46 //        }
47         System.out.println("list:" + list);
48         //list:[hello, world, java, javaee]
49     }
50 }


(6)常见数据结构
A:栈 先进后出
B:队列 先进先出
C:数组 查询快,增删慢
D:链表 查询慢,增删快


(7)List的子类特点
ArrayList
底层数据结构是数组,查询快,增删慢。
线程不安全,效率高。
Vector
底层数据结构是数组,查询快,增删慢。
线程安全,效率低。
LinkedList
底层数据结构是链表,查询慢,增删快。
线程不安全,效率高。

到底使用谁呢?看需求?
分析:
要安全吗?
要:Vector(即使要,也不使用这个)
不要:ArrayList或者LinkedList
查询多;ArrayList
增删多:LinkedList

什么都不知道,就用ArrayList。

原文地址:https://www.cnblogs.com/lyywj170403/p/9378881.html