Comparison of comparator and comparable

Source: Internet
Author: User
Tags arrays comparable comparison sort

When you want to sort a collection or array that is not a simple numeric type, you can usually use comparator or comparable to implement an object sort or custom sort in a simple way.

First, Comparator

A comparison function that forces an overall sort on an object collection can pass comparator to Collections.sort or arrays.sort.

Interface method:

1 /** *//**
2  * @return o1小于、等于或大于o2,分别返回负整数、零或正整数。
3  */
4 int compare(Object o1, Object o2);案例:
1import java.util.Arrays;
2import java.util.Comparator;
3
4public class SampleComparator implements Comparator {
5
6 public int compare(Object o1, Object o2) {
7  return toInt(o1) - toInt(o2);
8 }
9
10 private int toInt(Object o) {
11  String str = (String) o;
12  str = str.replaceAll("一", "1");
13  str = str.replaceAll("二", "2");
14  str = str.replaceAll("三", "3");
15  return Integer.parseInt(str);
16 }
17
18 /** *//**
19  * 测试方法
20  */
21 public static void main(String[] args) {
22  String[] array = new String[] { "一二", "三", "二" };
23  Arrays.sort(array, new SampleComparator());
24  for (int i = 0; i < array.length; i++) {
25   System.out.println(array[i]);
26  }
27 }
28
29}

Second, comparable

The object list (and array) that implements this interface can be automatically sorted by Collections.sort or arrays.sort, by forcing an overall ordering of the objects for each class that implements it.

Interface method:

1 /** *//**
2  * @return 该对象小于、等于或大于指定对象o,分别返回负整数、零或 正整数。
3  */
4 int compareTo(Object o);假设对象User,需要按年龄排序:
1public class User {
2
3 private String id;
4 private int age;
5
6 public User(String id, int age) {
7  this.id = id;
8  this.age = age;
9 }
10
11 public int getAge() {
12  return age;
13 }
14
15 public void setAge(int age) {
16  this.age = age;
17 }
18
19 public String getId() {
20  return id;
21 }
22
23 public void setId(String id) {
24  this.id = id;
25 }
26
27}

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.