|
Academic Work Personal
|
Java /
Sorting a collection
For more info, see http://mindprod.com/jgloss/sort.html . Example #1Say we want to sort a family of bitsets in ascending order by size.
Vector<BitSet> set = ...;
Collections.sort(set, new BitsetComparatorBySize());
// ==============================
class BitsetComparatorBySize
implements Comparator<BitSet>
{
// compare two Bitsets (callback for sort)
// Effectively returns a-b; e.g.
// +1 (or any positive number) if a > b
// 0 if a == b
// -1 (or any negative number) if a < b
public final int compare(BitSet a, BitSet b) {
return ( ((BitSet) a).cardinality() - ((BitSet) b).cardinality() );
} // end compare
}
Or, compare two BitSets lexicographically:
public class BitsetComparer
implements Comparator<Object>
{
public int compare(Object o1, Object o2) {
return (((BitSet) o1).toString().compareTo(((BitSet) o2).toString()));
}
}
Example #2If you have your own class, you can define how to compare two objects of this class.
public class HashElem
implements Comparable<Object>
{
...
public int compareTo(Object o)
{
if (o==null || !(o instanceof HashElem)) {
throw new ClassCastException();
}
return (this.intent.toString().compareTo(((HashElem) o).getIntent().toString()));
}
} // eof class
|
![]() anime | bash | blogs | bsd | c/c++ | c64 | calc | comics | convert | cube | del.icio.us | digg | east | eBooks | egeszseg | elite | firefox | flash | fun | games | gimp | google | groovy | hardware | hit&run | howto | java | javascript | knife | lang | latex | liferay | linux | lovecraft | magyar | maths | movies | music | p2p | perl | pdf | photoshop | php | pmwiki | prog | python | radio | recept | rts | scala | scene | sci-fi | scripting | security | shell | space | súlyos | telephone | torrente | translate | ubuntu | vim | wallpapers | webutils | wikis | windows Blogs and Dev. * Ubuntu Incident Places Debrecen | France | Hungary | Montreal | Nancy Notes Hobby Projects * Jabba's Codes Quick Links [ edit ] |