1. 程式人生 > >Java 中Collections類的用法

Java 中Collections類的用法

參考:

Collections類常用方法總結

1. 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)

在使用List時想根據List中儲存物件的某一欄位進行排序,那麼我們要用到Collections.sort方法對list排序,用Collections.sort方法對list排序有兩種方法:

  • 第一種是list中的物件實現Comparable介面;
  • 第二種方法是根據Collections.sort過載方法來實現。

demo:

public class SortTest {
    public static void main(String[] args) {
        List<String> listS = new ArrayList<String>();
        List<Employer1> list1 = new ArrayList<Employer1>();
        List<Employer2> list2 = new ArrayList<Employer2>();
        List<Employer3> list3 = new ArrayList<Employer3>();
        
        //一.將String型別的變數插入到listS中並排序
        //listS中的物件String 本身含有compareTo方法,所以可以直接呼叫sort方法,按自然順序排序,即升序排序
        listS.add("5");
        listS.add("2");
        listS.add("9");
        Collections.sort(listS);
        
        //二.將Employer1類的物件插入到list1中並排序
        //將已建立的實現了Comparator介面的比較類MyCompare傳入Collections的sort方法中即可實現依照MyCompare類中的比較規則。
        Employer1 a1 = new Employer1();
        Employer1 b1 = new Employer1();
        Employer1 c1 = new Employer1();
        a1.setName("a1");   a1.setAge(44);
        b1.setName("b1");   b1.setAge(55);
        c1.setName("b1");   c1.setAge(33);
        list1.add(a1);
        list1.add(b1);
        list1.add(c1);//Collections類的sort方法要求傳入的第二個引數是一個已實現Comparator介面的比較器
        Collections.sort(list1, new MyCompare());

        //三.將Employer2類的物件插入到list2中並排序
        //其實原理和上面的二類似,只是沒有單獨建立MyCompare類,而是用匿名內部類來實現Comparator接口裡面的具體比較。
        Employer2 a2 = new Employer2();
        Employer2 b2 = new Employer2();
        Employer2 c2 = new Employer2();
        a2.setName("a2");   a2.setAge(66);
        b2.setName("b2");   b2.setAge(33);
        c2.setName("b2");   c2.setAge(22);
        list2.add(a2);
        list2.add(b2);
        list2.add(c2); //Collections類的sort方法要求傳入的第二個引數是一個已實現Comparator介面的比較器
        Collections.sort(list2,new Comparator<Employer2>(){
            @Override
            public int compare(Employer2 a2, Employer2 b2) {
                return a2.getOrder().compareTo(b2.getOrder());
            }

        });

        //四.將Employer3類的物件插入到list3中並排序
        //被排序的類Employer3實現了Comparable介面,在類Employer3中通過過載compareTo方法來實現具體的比較。
        Employer3 a3 = new Employer3();
        Employer3 b3 = new Employer3();
        Employer3 c3 = new Employer3();
        a3.setName("a3");   a3.setAge(77);
        b3.setName("b3");   b3.setAge(55);
        c3.setName("b3");   c3.setAge(99);
        list3.add(a3);
        list3.add(b3);
        list3.add(c3);
        Collections.sort(list3);//Collections類的sort方法要求傳入的List中的物件是已實現Comparable介面的物件

        System.out.println(listS);
        System.out.println(list1);
        System.out.println(list3);
        System.out.println(list2);
    }
}
class Employer1{
    private String name;
    private Integer age;
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override//過載了Object類裡的toString方法,使之可以按照我們要求的格式列印
    public String toString() {
        return "name is "+name+" age is "+ age;
    }
}
class MyCompare implements Comparator<Employer1> {
    @Override//過載了Comparator接口裡面的compare方法實現具體的比較
    public int compare(Employer1 o1, Employer1 o2) {
        return o1.getAge().compareTo(o2.getAge());
    }
}
class Employer2{
    private String name;
    private Integer age;
    public void setName(String name) {
        this.name = name;
    }
    public Integer getOrder() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override//過載了Object類裡的toString方法,使之可以按照我們要求的格式列印
    public String toString() {
        return "name is "+name+" age is "+age;
    }
}
class Employer3 implements Comparable<Employer3>{
    private String name;
    private Integer age;
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override//過載了Object類裡的toString方法,使之可以按照我們要求的格式列印
    public String toString() {
        return "name is "+name+" age is "+age;
    }
    @Override//過載了Comparable接口裡的compareTo方法來實現具體的比較
    public int compareTo(Employer3 a) {
        return this.age.compareTo(a.getAge());
    }
}

列印結果:

[2, 5, 9]
[name is b1 age is 33, name is a1 age is 44, name is b1 age is 55]
[name is b3 age is 55, name is a3 age is 77, name is b3 age is 99]
[name is b2 age is 22, name is b2 age is 33, name is a2 age is 66]

compareTo()小結

  由上面的程式我們可以看出,無論是實現了Comparable介面的方法還是實現了Comparator介面的方法,最終比較的返回值都是通過compareTo方法實現的,故就把compareTo方法單獨拿出來做個小結。

  compareTo()的返回值是整型,它是先比較對應字元的大小(ASCII碼順序),如果第一個字元和引數的第一個字元不等,結束比較,返回他們之間的差值,如果第一個字元和引數的第一個字元相等,則以第二個字元和引數的第二個字元做比較,以此類推,直至比較的字元或被比較的字元有一方全比較完,這時就比較字元的長度。例如:

String s1 = "abc"; 
String s2 = "abcd"; 
String s3 = "abcdfg"; 
String s4 = "1bcdfg"; 
String s5 = "cdfg"; 
System.out.println( s1.compareTo(s2) ); // -1 (前面相等,s1長度小1) 
System.out.println( s1.compareTo(s3) ); // -3 (前面相等,s1長度小3) 
System.out.println( s1.compareTo(s4) ); // 48 ("a"的ASCII碼是97,"1"的的ASCII碼是49,所以返回48) 
System.out.println( s1.compareTo(s5) ); // -2 ("a"的ASCII碼是97,"c"的ASCII碼是99,所以返回-2)

2. shuffle

對集合進行隨機排序

 public static void shuffle(List<?> list)

 public static void shuffle(List<?> list, Random rnd)

demo:

public class Practice {
    public static void main(String[] args){
        List c = new ArrayList();
        c.add("w");
        c.add("o");
        c.add("r");
        c.add("l");
        c.add("d");
        System.out.println(c);
        Collections.shuffle(c);
        System.out.println(c);
        Collections.shuffle(c);
        System.out.println(c);
    }
}

結果:

[w, o, r, l, d]
[l, d, w, o, r]
[o, r, d, l, w]

3. binarySearch

查詢指定集合中的元素,返回所查詢元素的索引,如果它包含在陣列中,則返回搜尋鍵的索引;否則返回 (-(插入點) - 1)。 插入點 被定義為將鍵插入陣列的那一點:即第一個大於此鍵的元素索引,如果陣列中的所有元素都小於指定的鍵,則為 a.length。注意,這保證了當且僅當此鍵被找到時,返回的值將 >= 0。

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)

demo:

public class Practice {
    public static void main(String[] args){
        List c = new ArrayList();
        c.add("l");
        c.add("o");
        c.add("v");
        c.add("e");
        System.out.println(c);
        int m = Collections.binarySearch(c, "o");
        int n = Collections.binarySearch(c, "p");
        System.out.println(m + "    " + n);
    }
}

結果:

[l, o, v, e]
1    -3

4. max

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)

前者採用Collection內含自然比較法,後者採用Comparator進行比較.

5. min

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)

前者採用Collection內含自然比較法,後者採用Comparator進行比較。

6. indexOfSubList

查詢subList在list中首次出現位置的索引

public static int indexOfSubList(List<?> source,List<?> target)

demo:

public class Practice {
  public static void main(String[] args){
    List list = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(list);
    List subList = Arrays.asList("three four five six".split(" "));
    System.out.println(Collections.indexOfSubList(list, subList));
  }
}

結果:

[one, two, three, four, five, six, siven]
2

7. lastIndexOfSubList

使用與上例方法的使用相同。

8. replaceAll

替換批定元素為某元素,若要替換的值存在剛返回true,反之返回false

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

demo:

public class Practice {
  public static void main(String[] args){
    List list = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(list);
    List subList = Arrays.asList("three four five six".split(" "));
    System.out.println(Collections.replaceAll(list, "siven", "siven eight"));
    System.out.println(list);
  }
}

執行結果為:
[one, two, three, four, five, six, siven]
true
[one, two, three, four, five, six, siven eight]

9. reverse()

反轉集合中元素的順序

public static void reverse(List<?> list)

demo:

public class Practice {
  public static void main(String[] args){
    List list = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(list);
    Collections.reverse(list);
    System.out.println(list);
  }
}

執行結果為:
[one, two, three, four, five, six, siven]
[siven, six, five, four, three, two, one]

10. rotate

集合中的元素向後移m個位置,在後面被遮蓋的元素迴圈到前面來

 public static void rotate(List<?> list, int distance)

demo:

public class Practice {
  public static void main(String[] args){
    List list = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(list);
    Collections.rotate(list, 1);
    System.out.println(list);
  }
}
執行結果為:
[one, two, three, four, five, six, siven]
[siven, one, two, three, four, five, six]

11. copy

將集合n中的元素全部複製到m中,並且覆蓋相應索引的元素

1 public static <T> void copy(List<? super T> dest,  List<? extends T> src)
demo:
public class Practice {
  public static void main(String[] args){
    List m = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(m);
    List n = Arrays.asList("我 是 複製過來的哈".split(" "));
    System.out.println(n);
    Collections.copy(m,n);
    System.out.println(m);
  }
}
執行結果為:
[one, two, three, four, five, six, siven]
[one, two, four, three, five, six, siven]

12. swap

交換集合中指定元素索引的位置

public static void swap(List<?> list,int i,int j)
demo:
public class Practice {
  public static void main(String[] args){
    List m = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(m);
    Collections.swap(m, 2, 3);
    System.out.println(m);
  }
}
執行結果為:
[one, two, three, four, five, six, siven]
[one, two, four, three, five, six, siven]

13. fill

用物件o替換集合list中的所有元素

public static <T> void fill(List<? super T> list, T obj)
demo:
public class Practice {
  public static void main(String[] args){
    List m = Arrays.asList("one two three four five six siven".split(" "));
    System.out.println(m);
    Collections.fill(m, "haha52T25xixi");
    System.out.println(m);
  }
}
執行結果為:
[one, two, three, four, five, six, siven]
[haha52T25xixi, haha52T25xixi, haha52T25xixi, haha52T25xixi, haha52T25xixi, haha52T25xixi, haha52T25xixi]

14. nCopies

返回大小為n的List,List不可改變,其中的所有引用都指向o

 public static <T> List<T> nCopies(int n, T o)
demo: 
public class Practice {
   public static void main(String[] args){
     System.out.println(Collections.nCopies(5, "haha"));
   }
 }

執行結果為:
[haha, haha, haha, haha, haha]