How to sort arrays and collections in Java

Source: Internet
Author: 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);//sorting array
Arrays.sort (Al.toarray ())//To sort list
System.out.println (AL);
}

}


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

Output results: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

1. If the iterator is allowed to traverse the list Al and add data to Al, a problem arises: the iterator needs no

Traverse the added data. So the list is locked when the iterator iterates through the list in Java, and it is not allowed to add or delete the

Data. So if you perform an iterator traversal, you'll report "Concurrency modification exceptions."

Exception in thread "main" java.util.ConcurrentModificationException

2. If you want to sort the array, use the Java.util.Arrays.sort () method.

If you sort the list, use the Java.util.Collections.sort () method.


The copyonwritearraylist in 3.java is specifically designed to handle concurrent list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.