Java implementation collection, file, array ordering

Source: Internet
Author: User
Tags arrays comparable sort

System.out.print ("before sort:");

for (int i = 0; i< arr.length; i++)

System.out.print (Arr[i] + "");

System.out.println ();

Arrays.sort (arr);

System.out.print ("after sort:");

for (int i = 0; i< arr.length; i++)

System.out.print (Arr[i] + "");

System.out.println ();

Output results:

Before Sort:2 3 1 10 7 4

After Sort:1 2 3 4 7 10

We see that the sort results are sorted in ascending order, as is the order below.

Sorting of objects

objects can be placed in an array, the same call to Arrays.sort (object[] arr) can be placed in the set, with the Java.util.Collections sort (list list).

But this class must implement the Java.lang.Comparable interface. This interface has only one method: int Compartto (Object o),

Returns a positive integer when this object is larger than the object passed in. Take class programmer as an example:

Class Programmer implements Comparable{

private String name;

Private String language;

private double pay;

Public Programmer (string name, String language, double pay) {

THIS.name = name;

This.language = language;

This.pay = pay;

}

public int compareTo (Object o) {

Programmer other = (programmer) o;

return (int) pay-(int) Other.pay;

}

Public String toString () {

Return ' {name: ' + name + ', language: "+ language +", Money: "+ Pay +"} ";

}

}

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.