这是完整的代码:
StringIntTuple.java:
public class StringIntTuple{ public final int intValue; public final String stringValue; public StringIntTuple(int intValue, String stringValue){ this.intValue = intValue; this.stringValue = stringValue; } public String toString(){ return "(" + this.intValue + ", " + this.stringValue + ")"; }}
StringIntTupleStringComparator.java:
import java.util.Comparator;public class StringIntTupleStringComparator implements Comparator<StringIntTuple> { @Override public int compare(StringIntTuple a, StringIntTuple b) { // TODO Auto-generated method stub return a.stringValue.compareTo(b.stringValue); }}
StringIntTupleIntComparator.java:
import java.util.Comparator;public class StringIntTupleIntComparator implements Comparator<StringIntTuple> { @Override public int compare(StringIntTuple a, StringIntTuple b) { return ((Integer)a.intValue).compareTo((Integer)b.intValue); }}
Driver.java:
import java.util.ArrayList;import java.util.Collections;public class Driver { public static String[] names = new String[] {"Monkey1", "Dog2", "Horse3", "Cow4", "Spider5"}; public static int[] data = new int[] {1,2,3,4,5}; public static void main(String[] args) { ArrayList<StringIntTuple> list = new ArrayList<StringIntTuple>(); for(int i =0; i<names.length; i++){ list.add(new StringIntTuple(data[i],names[i])); } Collections.sort(list, new StringIntTupleIntComparator()); System.out.println(list.toString()); Collections.sort(list, new StringIntTupleStringComparator()); System.out.println(list.toString()); }}
输出(首先按int字段排序,然后按String字段排序):
[(1,Monkey1),(2,Dog2),(3,Horse3),(4,Cow4),(5,Spider5)]
[(4,Cow4),(2,Dog2),(3,Horse3),(1,Monkey1),(5,Spider5)]
编辑1(额外信息):
如果您想使它适用于任何元组,即不将字段类型限制为int,String,则可以使用泛型简单地执行相同的 *** 作,即:
public class Tuple<A,B>{ public Tuple(A aValue, B bValue){ this.aValue = aValue; this.bValue = bValue; } public final A aValue; public final B bValue;}
然后,只需对比较器进行相应的调整,就可以得到一个通用的解决方案。编辑2(午餐后):在这里。
public class TupleAComparator<A extends Comparable<A>,B extends Comparable<B>> implements Comparator<Tuple<A,B>> { @Override public int compare(Tuple<A, B> t1, Tuple<A, B> t2) { return t1.aValue.compareTo(t2.aValue); }}
编辑3:代码补充,作为对注释1(增强注释2)的答复:TupleArrayList.java:
import java.util.ArrayList;import java.util.List;public class TupleArrayList<A,B> extends ArrayList<Tuple<A,B>> { private static final long serialVersionUID = -6931669375802967253L; public List<A> GetAValues(){ ArrayList<A> aArr = new ArrayList<A>(this.size()); for(Tuple<A,B> tuple : this){ aArr.add(tuple.aValue); } return aArr; } public List<B> GetBValues(){ ArrayList<B> bArr = new ArrayList<B>(this.size()); for(Tuple<A,B> tuple : this){ bArr.add(tuple.bValue); } return bArr; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)