JavaRush /Java Blog /Random EN /Using Java Arrays.sort() on any list of objects

Using Java Arrays.sort() on any list of objects

Published in the Random EN group
Sorting can be tricky, especially if your list Listcontains object wrappers ( Byte, Integer, Short, Long, Double, Float) rather than primitive numeric data types. I suggest using a method that can be very useful for solving simple problems or answering an interviewer’s question. Using Java Arrays.sort() on any list of objects - 1First, let's choose what we will fill our List. In this example I will use a list of graph edges ( Edges) from a simple data structure Graph:
// Очень простой класс Edge (рёбро графа)
public class Edge {
    public Vertex src;
    public Vertex dst;
    public double cost;

    // создание ребра между двух вершин
    Edge(Vertex s, Vertex d, double c) {
        src = s;
        dst = d;
        cost = c;
// Список рёбер
Edge[] edges = graph.getEdges();

What is a graph?

In discrete mathematics, a graph is defined as a pair of sets ( V, E), where Vis a subset of an arbitrary countable set, and Eis a subset ( VхV).

Probably, for those who are not accustomed to mathematical abstractions, such a definition will not be very clear, so let’s say it more simply:

A graph is a collection of vertices and edges connecting them. A good example of a graph that will immediately take it from the realm of abstraction to the realm of the material is a map of railway tracks.

The vertices of such a graph are stations . Well, the paths between them are edges .

Then we define the implementation of the interface java.util.Comparator:
class SortByCost implements Comparator<Edge> {
    public int compare(Edge a, Edge b) {
        if ( a.cost < b.cost ) return -1;
        else if ( a.cost == b.cost ) return 0;
        else return 1;
In this example, we will sort the edges of the graph by their weight, or by the distance from the vertex src (source) to the vertex dst (destination). Finally, we use the standard method java.util.Arrays.sort ():
Arrays.sort(edges, new SortByCost())
Now our sheet filled with objects Edgesis sorted in ascending order (from smallest to largest). The author of the solution is Ethan Arrowood.