我是一名C++程序员,目前我正在使用Java(我确实有相当多的Java经验).
基本上,我想重新创建pair<int,int>
我在C++中常用的东西,我想让它按第二个整数值排序.
我正在互联网上搜索并尝试不同的方法来解决这个问题,包括使用Comparator,Comparable等.
我基本上创建一个看起来像这样的测试程序:
import java.math.*;
import java.util.*;
import java.io.*;
import java.text.*;
class PairTest
{
public static void main (String args[]) // entry point from OS
{
new PairTest().run();
}
public void run (){
Pair foo = new Pair(1,2);
System.out.println(foo.first + " "+ foo.second);
ArrayList <Pair> al = new ArrayList<Pair>();
for(int i =10;i>0;i--){
al.add(new Pair(i, i*2));
}
for(int i =0;i<al.size();i++){
System.out.println(al.get(i).first + " " + al.get(i).second);
}
Collections.sort(al);
for(int i =0;i<al.size();i++){
System.out.println(al.get(i).first + " " + al.get(i).second);
}
}
private class Pair implements Comparable{
public int first;
public int second;
public Pair (int a, int b){
this.first = a;
this.second = b;
}
int compareTo (Pair o){
return new Integer(this.second).compareTo(new Integer(o.second));
}
}
}
Run Code Online (Sandbox Code Playgroud)
制作自定义排序函数的最佳方法是什么,以便ArrayList按"第二"变量排序.我想要一种快速而安全的方法,目前,编译器告诉我"PairTest.Pair不会覆盖抽象方法compareTo ......"
我真的不知道发生了什么,任何帮助将不胜感激.
您的Pair
类有两个问题:它不声明泛型参数,并且compareTo
方法需要public
.此外,返回int值之间的差异比构造Integer
对象和调用更有效compareTo
.试试这个:
private class Pair implements Comparable<Pair> {
public int first;
public int second;
public Pair (int a, int b){
this.first = a;
this.second = b;
}
public int compareTo (Pair o){
return second < o.second ? -1 : (second == o.second ? 0 : 1);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
526 次 |
最近记录: |