Best way for custom sorting in Java?

Demonkunga

New Member
I am a C++ programmer and I am using Java at the moment (I do have a considerable amount of java experience).Basically, I want to recreate the \[code\]pair<int,int>\[/code\] that I so commonly use in C++ and I want to have it sorted by the second integer value.I am searching up on the internet and trying different ways of going about this, including using Comparator, Comparable etc.I am basically creating a test program that looks like this:\[code\]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)); } }}\[/code\]What would be the best way to go about making a custom sorting function so the ArrayList sorts by the "second" variable. I want a quick and safe way of doing it, and at the moment, the compiler is telling me that "PairTest.Pair does not override abstract method compareTo..."I really don't know whats going on, any help would be greatly appreciated.
 
Top