Ordering of elements within Collection,arrays in Java (Application of Comparable,comparator interface)

Source: Internet
Author: User
Tags class definition comparable

In our usual use of collection, it is very often necessary to sort the elements inside. For this sort, there are usually two ways to implement this:

1. Create a comparator class to implement the comparator interface, and then apply the sort method provided by the collection internally. For example, the edges in the graph are sorted by their weight size (the second method is also described in the following example).

The Edge Edge is implemented as follows:

public class edge{

Vertex s,t;

Double weight;

。。。

}

We implement the comparator class definition as follows:

The methods for sorting are as follows:

public void sort (list<edge> edges) {

Edgecomparator comparator = new Edgecomparator ();

Collections.sort (Edges,comparator);

}

This allows us to sort the edge in edges by the size of its weights. In our practical application, you can adjust it according to your own needs.

2. Let your ADT implement the comparable interface, and then override the CompareTo () method. The difference between this approach and comparator is that there is no need to construct a new comparator class, and the comparison code is placed inside ADT.

Thus we rewrite the following edge classes as defined above:

Then apply collections.sort (edges) to sort the edges.

Ordering of elements within Collection,arrays in Java (Application of Comparable,comparator interface)

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.