问题描述
所以,我有一个包含其他类对象作为其数据成员的类。我创建了基于该原型的ArrayList。这里是code:
So, I have a class which contains another class object as its data member. I have created an ArrayList based on this prototype. Here is the code:
package Stack;
import java.io.*;
import java.util.*;
class Point
{
int x;
int y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class MergeInterval
{
Point P;
MergeInterval() {}
public static void main(String args[])
{
ArrayList<Point> arr = new ArrayList<Point>();
// Point p = new Point(6,8);
arr.add(new Point(6,8));
arr.add(new Point(1,9));
arr.add(new Point(2,4));
arr.add(new Point(4,7));
// System.out.println(arr.get(1).x + " " + arr.get(1).y);
}
}
我需要排序此ArrayList才能得到输出如下:
{1,9} {2,4} {4,7} {6,8}
I need to sort this Arraylist as to get the output as following:{1,9} {2,4} {4,7} {6,8}
基本上,我需要进行排序基于阶级点,但使用内置的排序方法的变量x这样的结构。我该如何实现呢?
Basically I needed to sort this structure based on the 'x' variable of Class 'Point' but using the inbuilt 'sort' method. How do I achieve it?
推荐答案
的需要的决定如何列表中的元素应互相比较以确定该命令的目的。您可以实施比较
亲自指定通过比较在点
取值应该比较它们的 X
的价值观,这需要code的几行,或者您可以使用内置的比较
取值之一。
The List.sort(...)
method takes a Comparator
which determines how the elements in the list should be compared to each other for the purposes of determining the order. You can either implement Comparator
yourself to specify that the Point
s should be compared by comparing their x
values, which takes several lines of code, or you can use one of the built-in Comparator
s.
的比较
接口定义,你想通过东西是列表元素的简单函数来比较的情况下默认实现。
The Comparator
interface defines default implementations for the case where you want to compare via something that is a simple function of the list element.
由于您是在 INT
属性比较,你可以使用 Comparator.comparingInt
如下:
Since you are comparing on an int
property, you can use Comparator.comparingInt
as follows:
arr.sort(Comparator.comparingInt(p -> p.x));
这篇关于基于排序类的数据成员的数据成员的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!