【JAVA集合框架之工具类】

一、概述

JAVA集合框架中有两个很重要的工具类,一个是Collections,另一个是Arrays。分别封装了对集合的操作方法和对数组的操作方法,这些操作方法使得程序员的开发更加高效。

public class Collections extends Object      全类名:java.util.Collections 
public class Arrays extends Object           全类名:java.util.Arrays 

二.Collections类。

1.Collections.sort方法。

public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list, Comparator<? super T> c)

(1)示例。

现在有一些字符串,可能有重复元素,想要将它们存入一个容器中并按照一定的规则进行排序,该怎么做?

思路:使用ArrayList集合进行存储并使用Collections.sort方法进行排序。

 1 package p01.ColletionsDemo.p01.SortDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 
 6 public class SortDemo {
 7 
 8     public static void main(String[] args) {
 9         Demo1();
10 
11     }
12     private static void Demo1() {
13         ArrayList<String>al=new ArrayList<String>();
14         al.add("abc");
15         al.add("bca");
16         al.add("aab");
17         al.add("bac");
18         al.add("cba");
19         System.out.println("排序前:"+al);
20         Collections.sort(al);
21         System.out.println("排序后:"+al);
22     }
23 
24 }
View Code

这是按照字符串的自然排序方式排序的代码,即输出结果的字符串是按照字典序排序的。

现在有了新的需求,即按照字符串长度排序,如果字符串长度相同按照字典序排序,这时候需要使用比较器。

 1 package p01.ColletionsDemo.p01.SortDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 public class SortDemo {
 8     public static void main(String[] args) {
 9         //Demo1();
10         Demo2();
11     }
12     /*
13      * Demo2:该方法采用带比较器的Collections.sort方法
14      */
15     private static void Demo2() {
16         ArrayList<String>al=new ArrayList<String>();
17         al.add("abcd");
18         al.add("abc");
19         al.add("bc");
20         al.add("aabadsf");
21         al.add("b");
22         al.add("cbae");
23         al.add("bade");
24         System.out.println("排序前:"+al);
25         Collections.sort(al,new ComparatorByLength());
26         System.out.println("排序后:"+al);
27     }
28     /*
29      * Demo1:该方法使用的是不带比较器的Collections.sort方法。
30      */
31     private static void Demo1() {
32         ArrayList<String>al=new ArrayList<String>();
33         al.add("abc");
34         al.add("abc");
35         al.add("bca");
36         al.add("aab");
37         al.add("bac");
38         al.add("cba");
39         System.out.println("排序前:"+al);
40         Collections.sort(al);
41         System.out.println("排序后:"+al);
42     }
43 
44 }
45 class ComparatorByLength implements Comparator<String>
46 {
47 
48     @Override
49     public int compare(String o1, String o2) {
50         int temp=o1.length()-o2.length();
51         return temp==0?o1.compareTo(o2):temp;
52     }
53     
54 }
View Code

两个重载方法使用起来非常方便,但是其实现原理是什么也需要了解。

(2)模拟不使用比较器的sort方法。

  1 package p01.ColletionsDemo.p02.SortDemo;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 class Person implements Comparable<Person>
  7 {
  8 
  9     private String name;
 10     private int age;
 11     @Override
 12     public String toString() {
 13         return "Person [name=" + name + ", age=" + age + "]
";
 14     }
 15     public String getName() {
 16         return name;
 17     }
 18     public void setName(String name) {
 19         this.name = name;
 20     }
 21     public int getAge() {
 22         return age;
 23     }
 24     public void setAge(int age) {
 25         this.age = age;
 26     }
 27     public Person(String name, int age) {
 28         super();
 29         this.name = name;
 30         this.age = age;
 31     }
 32     public Person() {
 33         super();
 34     }
 35     @Override
 36     public int compareTo(Person o) {
 37         int temp=this.age-o.getAge();
 38         return temp==0?this.name.compareTo(o.getName()):temp;
 39     }
 40 }
 41 class Student extends Person
 42 {
 43 
 44     public Student() {
 45         super();
 46     }
 47 
 48     public Student(String name, int age) {
 49         super(name, age);
 50     }
 51     
 52 }
 53 class Worker extends Person
 54 {
 55 
 56     public Worker() {
 57         super();
 58     }
 59 
 60     public Worker(String name, int age) {
 61         super(name, age);
 62     }
 63     
 64 }
 65 
 66 public class SortDemo {
 67     /**
 68      * 该类模拟带不带比较器的Collections.sort方法。
 69      * @param args
 70      */
 71     public static void main(String[] args) {
 72 
 73         Demo1();
 74     }
 75 
 76     private static void Demo1() {
 77         ArrayList<Person>al=new ArrayList<Person>();
 78         al.add(new Person("lisi",24));
 79         al.add(new Person("wangwu",25));
 80         al.add(new Person("zhangsan",23));
 81         al.add(new Person("chenqi",27));
 82         al.add(new Person("zhaoliu",26));
 83         
 84         System.out.println("排序前:"+al);
 85         MyCollections.sort(al);
 86         System.out.println("排序后:"+al);
 87     }
 88 
 89 }
 90 /*
 91  * 使用自定义Collections类
 92  */
 93 class  MyCollections
 94 {
 95     public static <T extends Comparable<? super T>> void  sort(List <T>list)
 96     {
 97         for(int i=0;i<=list.size()-2;i++)
 98         {
 99             for(int j=i+1;j<=list.size()-1;j++)
100             {
101                 if( list.get(i).compareTo(list.get(j))>0)
102                 {
103                     T t=list.get(i);
104                     list.set(i, list.get(j));
105                     list.set(j, t);
106                 }
107             }
108         }
109     }
110 }
View Code

改程序的核心就是MyColletions类了:

 1 class  MyCollections
 2 {
 3     public static <T extends Comparable<? super T>> void  sort(List <T>list)
 4     {
 5         for(int i=0;i<=list.size()-2;i++)
 6         {
 7             for(int j=i+1;j<=list.size()-1;j++)
 8             {
 9                 if( list.get(i).compareTo(list.get(j))>0)
10                 {
11                     T t=list.get(i);
12                     list.set(i, list.get(j));
13                     list.set(j, t);
14                 }
15             }
16         }
17     }
18 }
View Code

 (3)模拟使用比较器的sort方法。

  1 package p01.ColletionsDemo.p03.SortDemo;
  2 
  3 
  4 import java.util.ArrayList;
  5 import java.util.Arrays;
  6 import java.util.Comparator;
  7 import java.util.List;
  8 import java.util.ListIterator;
  9 
 10 class Person implements Comparable<Person>
 11 {
 12 
 13     private String name;
 14     private int age;
 15     @Override
 16     public String toString() {
 17         return  "name="+name + ", age=" + age +"
";
 18     }
 19     public String getName() {
 20         return name;
 21     }
 22     public void setName(String name) {
 23         this.name = name;
 24     }
 25     public int getAge() {
 26         return age;
 27     }
 28     public void setAge(int age) {
 29         this.age = age;
 30     }
 31     public Person(String name, int age) {
 32         super();
 33         this.name = name;
 34         this.age = age;
 35     }
 36     public Person() {
 37         super();
 38     }
 39     @Override
 40     public int compareTo(Person o) {
 41         int temp=this.age-o.getAge();
 42         return temp==0?this.name.compareTo(o.getName()):temp;
 43     }
 44 }
 45 class Student extends Person
 46 {
 47 
 48     @Override
 49     public String toString() {
 50         return  super.toString() ;
 51     }
 52 
 53     public Student() {
 54         super();
 55     }
 56 
 57     public Student(String name, int age) {
 58         super(name, age);
 59     }
 60     
 61 }
 62 class Worker extends Person
 63 {
 64 
 65     @Override
 66     public String toString() {
 67         return super.toString();
 68     }
 69 
 70     public Worker() {
 71         super();
 72     }
 73 
 74     public Worker(String name, int age) {
 75         super(name, age);
 76     }
 77     
 78 }
 79 
 80 public class SortDemo {
 81     /**
 82      * 该类模拟带不带比较器的Collections.sort方法。
 83      * @param args
 84      */
 85     public static void main(String[] args) {
 86 
 87 //        Demo1();
 88 //        Demo2();
 89         Demo3();
 90     }
 91 
 92     private static void Demo3() {
 93         ArrayList<Student>al=new ArrayList<Student>();
 94         al.add(new Student("lisi",24));
 95         al.add(new Student("wangwu",25));
 96         al.add(new Student("zhangsan",23));
 97         al.add(new Student("chenqi",27));
 98         al.add(new Student("zhaoliu",26));
 99         
100         System.out.println("排序前:"+al);
101         MyCollections_1.sort(al,new ComparatorByLength());
102         //Collections.sort(al, new ComparatorByLength());
103         System.out.println("排序后:"+al);
104     }
105 
106     private static void Demo1() 
107     {
108         ArrayList<Person>al=new ArrayList<Person>();
109         al.add(new Student("lisi",24));
110         al.add(new Person("wangwu",25));
111         al.add(new Worker("zhangsan",23));
112         al.add(new Person("chenqi",27));
113         al.add(new Person("zhaoliu",26));
114         
115         System.out.println("排序前:"+al);
116         
117         System.out.println("排序后:"+al);
118     }
119 
120 }
121 class  MyCollections_1
122 {
123     public static <T> void  sort(List <T>list,Comparator<? super T> c)
124     {
125         Object [] a = list.toArray();
126         Arrays.sort(a, (Comparator)c);
127         ListIterator i = list.listIterator();
128         for (int j=0; j<a.length; j++) 
129         {
130             i.next();
131             i.set(a[j]);
132         }
133     }
134 }
135 class ComparatorByLength implements Comparator<Person>
136 {
137     @Override
138     public int compare(Person o1, Person o2) {
139         int temp=o1.getName().length()-o2.getName().length();
140         return temp==0?o1.getName().compareTo(o2.getName()):temp;
141     }
142 }
View Code

改造程序的核心是:

 1 class  MyCollections_1
 2 {
 3     public static <T> void  sort(List <T>list,Comparator<? super T> c)
 4     {
 5         Object [] a = list.toArray();
 6         Arrays.sort(a, (Comparator)c);
 7         ListIterator i = list.listIterator();
 8         for (int j=0; j<a.length; j++) 
 9         {
10             i.next();
11             i.set(a[j]);
12         }
13     }
14 }
15 class ComparatorByLength implements Comparator<Person>
16 {
17     @Override
18     public int compare(Person o1, Person o2) {
19         int temp=o1.getName().length()-o2.getName().length();
20         return temp==0?o1.getName().compareTo(o2.getName()):temp;
21     }
22 }
View Code

其实,Collectios.sort方法的实质就是将集合转换成数组,然后使用Arrays工具类的sort方法进行排序,最后根据排序结果修改原集合。

2.Collections.binarySearch方法。

public static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key)
public static <T> int binarySearch(List<? extends T> list,T key,Comparator<? super T> c)

这两个方法中,前者是不带比较器的二分查找方法,后者是带着比较器的二分查找方法。

既然是二分查找法,那么集合中的元素必然是有序的;如果元素不带有比自然比较的属性,则必须使用比较器,否则元素必须具备自然比较的属性,即实现了Comparable接口。

(1)简单的使用方法(不带比较器)演示

 1 package p02.ColletionsDemo.p01.BinarySearchDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 
 6 public class BinarySearchDemo {
 7 
 8     public static void main(String[] args) {
 9         Demo01();
10         Demo02();
11     }
12     /**
13      * 没经过排序的集合使用二分查找法
14      */
15     private static void Demo02() {
16         ArrayList<String>al=new ArrayList<String>();
17         al.add("abc");
18         al.add("dabdc");
19         al.add("cd");
20         al.add("bac");
21         al.add("ba");
22         System.out.println(al);
23         int index=Collections.binarySearch(al, "ba");
24         System.out.println(index);
25     }
26     /**
27      * 经过排序的集合使用二分查找法
28      */
29     private static void Demo01() {
30         ArrayList<String>al=new ArrayList<String>();
31         al.add("abc");
32         al.add("dabdc");
33         al.add("cd");
34         al.add("bac");
35         al.add("ba");
36         Collections.sort(al);
37         System.out.println(al);
38         int index=Collections.binarySearch(al, "ba");
39         System.out.println(index);
40     }
41 
42 }
View Code

如果没有找到关键字,则会返回一个负数,该负数是如果将该数插入集合应当插入的位置*-1-1。减一的目的是为了防止应当插入的位置是0。

(2)复杂的使用方法演示(存放自定义对象,并使用了自定义比较器)

 1 package p02.ColletionsDemo.p02.BinarySearchDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 class Person implements Comparable<Person>
 8 {
 9     public String name;
10     public int age;
11     
12     @Override
13     public String toString() {
14         return "Person [name=" + name + ", age=" + age + "]
";
15     }
16 
17     public Person(String name, int age) {
18         super();
19         this.name = name;
20         this.age = age;
21     }
22 
23     public Person() {
24         super();
25     }
26 
27     @Override
28     public int compareTo(Person o) {
29         int temp=this.age-o.age;
30         return temp==0?this.name.compareTo(o.name):temp;
31     }
32 }
33 public class BinarySearchDemo {
34     public static void main(String[] args) {
35         Demo01();
36         
37         /*
38          * 按照名字的字典序排序,并查找,如果名字相同,则按照年龄排序
39          */
40         Demo02();
41     }
42 
43     /*
44      * 使用带比较器的二分查找方法
45      */
46     private static void Demo02() {
47         ArrayList<Person>al=new ArrayList<Person>();
48         al.add(new Person("zhaoliu",26));
49         al.add(new Person("lisi",24));
50         al.add(new Person("zhangsan",23));
51         al.add(new Person("wangwu",25));
52         al.add(new Person("wangwu",23));
53         al.add(new Person("wangwu",22));
54         al.add(new Person("wangwu",21));
55         Collections.sort(al,new ComparatorByName());
56         System.out.println(al);
57         int index=Collections.binarySearch(al,new Person("wangwu",25),new ComparatorByName());
58         System.out.println(index);
59     }
60 
61     /*
62      * 不使用带比较器的二分查找方法。
63      */
64     private static void Demo01() {
65         ArrayList<Person>al=new ArrayList<Person>();
66         al.add(new Person("zhaoliu",26));
67         al.add(new Person("lisi",24));
68         al.add(new Person("zhangsan",23));
69         al.add(new Person("wangwu",25));
70         al.add(new Person("wangwu",23));
71         al.add(new Person("wangwu",22));
72         al.add(new Person("wangwu",21));
73         Collections.sort(al);
74         System.out.println(al);
75         int index=Collections.binarySearch(al,new Person("wangwu",25));
76         System.out.println(index);
77     }
78 
79 }
80 class ComparatorByName implements Comparator<Person>
81 {
82     @Override
83     public int compare(Person o1, Person o2) {
84         int temp=o1.name.compareTo(o2.name);
85         return temp==0?o1.age-o2.age:temp;
86     }
87     
88 }
View Code

 3.最大值最小值方法。

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
public static <T> T max(Collection<? extends T> coll,Comparator<? super T> comp)
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
public static <T> T min(Collection<? extends T> coll,Comparator<? super T> comp)
 1 package p03.ColletionsDemo.p01.MaxMainDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 public class MaxMinDemo {
 8 
 9     public static void main(String[] args) {
10         Demo01();
11 
12     }
13 
14     private static void Demo01() {
15         ArrayList<String>al=new ArrayList<String>();
16         al.add("bcade");
17         al.add("abc");
18         al.add("baefgh");
19         al.add("b");
20         /*
21          * 按照默认比较方式进行比较
22          */
23         String max=Collections.max(al);
24         String min=Collections.min(al);
25         System.out.println("max="+max);
26         System.out.println("min="+min);
27         
28         System.out.println();
29         /*
30          * 更改比较方式,按照长度进行比较
31          */
32         ComparatorByStringLength cbsl=new ComparatorByStringLength();
33         String max_1=Collections.max(al,cbsl);
34         String min_1=Collections.min(al,cbsl);
35         System.out.println("max="+max_1);
36         System.out.println("min="+min_1);
37     }
38 
39 }
40 /*
41  * 按照长度进行比较
42  */
43 class ComparatorByStringLength implements Comparator<String>
44 {
45     @Override
46     public int compare(String o1, String o2) {
47         int temp=o1.length()-o2.length();
48         return temp==0?o1.compareTo(o2):temp;
49     }    
50 }
View Code

4.反转和逆序。

public static void reverse(List<?> list)
public static <T> Comparator<T> reverseOrder()
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)
 1 package p04.ColletionsDemo.p01.ReverseOrderDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 public class ReverseOrderDemo {
 8 
 9     public static void main(String[] args) {
10         //直接得到逆序的比较器从而将结果逆序。
11         Demo01();
12         //将比较器逆序从而将结果逆序。
13         Demo02();
14     }
15 
16     /*
17      * 按照长度进行排序(自定义比较器)并逆序
18      */
19     private static void Demo02() {
20         ArrayList<String>al=new ArrayList<String>();
21         al.add("defefe");
22         al.add("edfef");
23         al.add("abce");
24         al.add("ba");
25         al.add("ab");
26         ComparatorByStringLength cbsl=new ComparatorByStringLength();
27         Collections.sort(al,cbsl);
28         System.out.println(al);
29         Collections.sort(al,Collections.reverseOrder(cbsl));//实现比较器的逆序。
30         System.out.println(al);
31     }
32 
33     private static void Demo01() {
34         ArrayList<String>al=new ArrayList<String>();
35         al.add("defefe");
36         al.add("edfef");
37         al.add("abce");
38         al.add("ba");
39         al.add("ab");
40         Collections.sort(al);
41         System.out.println(al);
42         Collections.sort(al,Collections.reverseOrder());//实现逆序
43         System.out.println(al);
44     }
45 }
46 /*
47  * 按照长度进行比较
48  */
49 class ComparatorByStringLength implements Comparator<String>
50 {
51     @Override
52     public int compare(String o1, String o2) {
53         int temp=o1.length()-o2.length();
54         return temp==0?o1.compareTo(o2):temp;
55     }    
56 }
View Code

5.替换。

public static <T> boolean replaceAll(List<T> list,T oldVal,T newVal)

使用这个方法的时候如果List中存放的是自定义对象,则应当复写equals方法。

 1 package p05.ColletionsDemo.p01.ReplaceAllDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 
 6 class Person
 7 {
 8     public String name;
 9     public int age;
10     public Person(String name, int age) {
11         super();
12         this.name = name;
13         this.age = age;
14     }
15     public Person() {
16         super();
17     }
18     @Override
19     public String toString() {
20         return "name=" + name + ", age=" + age + "
";
21     }
22     /*
23      * (non-Javadoc)
24      * @see java.lang.Object#equals(java.lang.Object)
25      * 如果想要使用Collections.repalceAll方法,则必须复写自定义对象的equals方法。
26      */
27     @Override
28     public boolean equals(Object obj) {
29         Person p=(Person)obj;
30         return this.age==p.age&&this.name==p.name?true:false;
31     }
32 }
33 
34 public class ReplaceAllDemo {
35 
36     public static void main(String[] args) {
37         Demo01();
38     }
39 
40     private static void Demo01() {
41         ArrayList<Person>al=new ArrayList<Person>();
42         al.add(new Person("zhangsan",23));
43         al.add(new Person("lisi",24));
44         al.add(new Person("wangwu",25));
45         al.add(new Person("zhaoliu",26));
46         
47         System.out.println(al);
48         Collections.replaceAll(al, new Person("zhangsan",23),new Person("chenqi",27));
49         System.out.println(al);
50     }
51 
52 }
View Code

6.最重要的问题:同步集合的问题。

Colletions类中提供了几种方法可以将非同步的集合转变成同步集合,这是为了满足在多线程环境下编程的需求。

public static <T> Collection<T> synchronizedCollection(Collection<T> c)
public static <T> List<T> synchronizedList(List<T> list)
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
public static <T> Set<T> synchronizedSet(Set<T> s)
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)

下面的代码实现了自定义同步集合以及使用上述方法生成的同步集合,两种方法相比较,很明显,使用工具类能够大大提高效率。注意自定义集合中泛型的使用。

 1 package p07.ColletionsDemo.p01.SynchronizedFunctionDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 public class SynchronizedFunctionDemo {
 9 
10     public static void main(String[] args) {
11         Demo01();//自定义同步集合
12         
13         Demo02();//使用Collecionts.xxx得到同步的集合
14     }
15 
16     private static void Demo02() {
17         /*
18          * 使用Collections提供的方法则要简单的多。
19          */
20         List<String>list=Collections.synchronizedList(new ArrayList<String>());
21         list.add("zhangsan");
22         list.add("lisi");
23         list.add("wangwu");
24         list.remove("lisi");
25         Iterator<String>it=list.iterator();
26         while(it.hasNext())
27         {
28             String str=it.next();
29             System.out.println(str);
30         }
31     }
32 
33     private static void Demo01() {
34         MyList <String>list=new MyList<String>(new ArrayList<String>());
35         list.add("zhangsan");
36         list.add("lisi");
37         list.add("wangwu");
38         list.remove("lisi");
39         Iterator<String>it=list.iterator();
40         while(it.hasNext())
41         {
42             String str=it.next();
43             System.out.println(str);
44         }
45     }
46 }
47 
48 /*
49  * 该类将List集合转换成同步的List集合,需要重新写许多方法,非常麻烦
50  */
51 class  MyList<E>
52 {
53     private List<E> list;
54     private final Object obj=new Object();
55     public MyList(){}
56     public MyList(List<E> list)
57     {
58         this.list=list;
59     }
60     public boolean add(E obj)
61     {
62         synchronized(obj)
63             {
64             return this.list.add(obj);
65             }
66     }
67     public boolean remove(E obj)
68     {
69         synchronized(obj)
70             {
71             return this.list.remove(obj);
72             }
73     }
74     public Iterator<E> iterator()
75     {
76         /*
77          * 没有涉及到元素的删除和添加就不加同步。
78          */
79         return this.list.iterator();
80     }
81 }
View Code

7.其它方法。

public static <T> Enumeration<T> enumeration(Collection<T> c)
public static <T> ArrayList<T> list(Enumeration<T> e)
public static <T> void fill(List<? super T> list,T obj)
public static void shuffle(List<?> list)
public static void shuffle(List<?> list,Random rnd)

下面只演示前两个方法:

 1 package p06.ColletionsDemo.p01.EnumerationAndListDemo;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Enumeration;
 6 import java.util.Iterator;
 7 import java.util.Vector;
 8 
 9 public class EnumerationAndListDemo {
10 
11     public static void main(String[] args) {
12         Demo01();
13         Demo02();
14     }
15 
16     private static void Demo02() {
17         Vector<String>v=new Vector<String>();
18         v.add("张三");
19         v.add("李四");
20         v.add("王五");
21         v.add("赵六");
22         
23         ArrayList<String>al=Collections.list(v.elements());//两点在这一行
24         Iterator<String>it=al.iterator();
25         while(it.hasNext())
26         {
27             String str=it.next();
28             System.out.println(str);
29         }
30         
31     }
32 
33     public static void Demo01() {
34         ArrayList<String>list=new ArrayList<String>();
35         list.add("zhangsan");
36         list.add("lisi");
37         list.add("wangwu");
38         list.add("zhaoliu");
39         Enumeration<String> e=Collections.enumeration(list);
40         while(e.hasMoreElements())
41         {
42             String str=e.nextElement();
43             System.out.println(str);
44         }
45     }
46 
47 }
View Code

三、Arrays类。

1.toString方法。

public static String toString(int[] a)

上述的方法只是一个例子,该方法由多种重载形式。可以接受的参数包括各种基本数据类型。

功能是返回指定数组内容的字符串表示形式。

 1 package p08.ArraysDemo.p01.ToStringDemo;
 2 
 3 import java.util.Arrays;
 4 
 5 public class ToStringDemo {
 6 
 7     public static void main(String[] args) {
 8         Demo01();
 9     }
10     private static void Demo01() {
11         int[]arr=new int[10];
12         for(int i=0;i<arr.length;i++)
13         {
14             arr[i]=i;
15         }
16         String str=Arrays.toString(arr);
17         System.out.println(str);
18     }
19 
20 }
View Code

该方法的使用方法很简单,但是我们应当注意其源码的实现形式,特别是对for循环的处理,是很值得借鉴的地方

 1  public static String toString(int[] a) {
 2         if (a == null)
 3             return "null";
 4         int iMax = a.length - 1;
 5         if (iMax == -1)
 6             return "[]";
 7 
 8         StringBuilder b = new StringBuilder();
 9         b.append('[');
10         for (int i = 0; ; i++) {
11             b.append(a[i]);
12             if (i == iMax)
13                 return b.append(']').toString();
14             b.append(", ");
15         }
16     }
View Code

上述代码中的for循环没有判断条件,这样就大大提高了代码效率。

2.asList方法。

public static <T> List<T> asList(T... a)

该方法使用了可变参数,这点应当注意。功能是返回一个受指定数组支持的固定大小的列表,也就是将数组转换成集合的方法。该方法的目的是使用更多的方法对数组的元素进行操作,毕竟数组中的方法并不多,即使有了Arrays方法也还是不够,如果能转换成集合进行操作,将能够使用更多更有效的方法,比如contains方法等。

 1 package p09.ArraysDemo.p01.AListDemo;
 2 
 3 import java.util.Arrays;
 4 import java.util.List;
 5 
 6 public class AlistDemo {
 7 
 8     public static void main(String[] args) {
 9         Demo01();
10         Demo02();
11     }
12 
13     /**
14      * 如果数组存放基本数据类型,则转变成集合之后存放的是数组的引用
15      */
16     private static void Demo02() {
17         int arr[]=new int[10];
18         for(int i=0;i<arr.length;i++)
19         {
20             arr[i]=i;
21         }
22         List<int[]>list_1=Arrays.asList(arr);
23         System.out.println(list_1);
24         
25         Integer arr_1[]=new Integer[10];
26         for(int i=0;i<arr.length;i++)
27         {
28             arr_1[i]=i;
29         }
30         List<Integer>list_2=Arrays.asList(arr_1);
31         System.out.println(list_2);
32     }
33 
34     /**
35      * 如果数组内存放对象,则存放的是一个个对象的内容
36      */
37     private static void Demo01() {
38         String arr[]=new String[10];
39         for(int i=0;i<arr.length;i++)
40         {
41             arr[i]=i+"";
42         }
43         List<String>list=Arrays.asList(arr);
44         System.out.println(list);
45     }
46 
47 }
View Code

注意,虽然该方法可以将数组转换成集合,但是不能进行增删操作,否则会有异常产生,这是因为数组就是数组的长度是不可变的。

3.集合转数组的方法:toArray。

集合转换成数组的目的一般就是减小对元素的操作权限,比如不允许增删操作了。

 1 package p10.ArraysDemo.p01.ListToArr;
 2 
 3 import java.util.ArrayList;
 4 
 5 public class ListToArr {
 6 
 7     public static void main(String[] args) {
 8         Demo01();
 9     }
10 
11     private static void Demo01() {
12         ArrayList <Integer>list=new ArrayList<Integer>();
13         list.add(1);
14         list.add(2);
15         list.add(3);
16         list.add(4);
17         System.out.println(list);
18         Integer []arr=list.toArray(new Integer[list.size()]);//将集合转变成数组,注意类型应当匹配,否则会抛出ArrayStoreException异常。
19         System.out.println(arr);
20         for(int i=0;i<arr.length;i++)
21         {
22             System.out.println(arr[i]);
23         }
24     }
25 
26 }
View Code
原文地址:https://www.cnblogs.com/kuangdaoyizhimei/p/4025021.html