java中如何對數組和集合進行排序

來源:互聯網
上載者:User

package com.hsy.interView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayAdd {

    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr1={1,3,5,7,9};
        int[] arr2={2,4,6,8,10};
        List<Comparable> al = new ArrayList<Comparable>();
       
        for(int i=0;i<arr1.length;i++){
            al.add(arr1[i]);
        }
       
        for(int j=0;j<arr2.length;j++){
            al.add(arr2[j]);
        }


   /*  Iterator<Comparable> it=al.iterator();
        Integer obj = null;
        while(it.hasNext()){
            obj=(Integer)it.next();   
            al.add(obj.intValue());
        }

        */
               
        Collections.sort(al);//對數組排序
        //Arrays.sort(al.toArray());//對list排序
        System.out.println(al);
    }

}


=================================================

輸出結果: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1.如果允許迭代器遍曆列表al時又向al中添加資料,那麼就會產生一個問題:迭代器需不需要 

   遍曆添加的資料。所以在Java中迭代器遍曆列表時會對列表加鎖,此時不允許增刪列表中的

   資料。因此如果執行迭代器遍曆的話就會報出【並發修改異常】

   Exception in thread "main" java.util.ConcurrentModificationException

2.如果要對數組排序,請使用java.util.Arrays.sort()方法.

   如果對list排序,請使用java.util.Collections.sort()方法.


3.java中的CopyOnWriteArrayList專門用來處理並發的List

       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.