Kun tietorakenteelta oletetaan tietty rajapinta, voidaan sille suorittaa sopiva algoritmi, esimerkiksi lajittelu, tietämättä tietorakenteen yksityiskohtia:
import java.util.ArrayList;
import java.util.Vector;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.io.*;
import fi.jyu.mit.ohj2.*;
/**
* Esimerkki Javan algoritmien käytöstä
* @author Vesa Lappalainen
* @version 1.0, 05.03.2002
*/
public class AlgoritmiMalli {
/**
* Luokka joka vertailee kahta kokonaislukuoliota ja
* palauttaa niiden järjestyksen niin, että lajittelu menee
* laskevaan järjestykseen.
*/
public static class LaskevaInt implements Comparator {
public int compare(Object o1, Object o2) {
return ((Integer)o2).intValue() - ((Integer)o1).intValue();
}
}
public static void tulosta(OutputStream os, Collection luvut) {
PrintStream out = Tiedosto.getPrintStream(os);
for (Iterator i = luvut.iterator(); i.hasNext(); ) {
int luku = ((Integer)i.next()).intValue();
out.print(luku + " ");
}
out.println();
}
public static void main(String[] args) {
ArrayList luvut = new ArrayList();
try {
luvut.add(new Integer(0)); luvut.add(new Integer(2));
luvut.add(new Integer(99)); luvut.add(new Integer(7));
luvut.add(new Integer(22)); luvut.add(new Integer(71));
} catch ( Exception e ) {
System.out.println("Virhe: " + e.getMessage());
}
System.out.println(luvut); // [0, 2, 99, 7, 22, 71]
Collections.sort(luvut);
tulosta(System.out,luvut); // 0 2 7 22 71 99
Collections.sort(luvut,new LaskevaInt());
tulosta(System.out,luvut); // 99 71 22 7 2 0
Collections.shuffle(luvut);
tulosta(System.out,luvut); // 99 2 7 71 0 22
Collections.sort(luvut,Collections.reverseOrder());
tulosta(System.out,luvut); // 99 71 22 7 2 0
Collections.reverse(luvut);
tulosta(System.out,luvut); // 0 2 7 22 71 99
int suurin = ((Integer)Collections.max(luvut)).intValue();
System.out.println("Suurin = " + suurin); // Suurin = 99
int pienin = ((Integer)Collections.min(luvut)).intValue();
System.out.println("Pienin = " + pienin); // Pienin = 0
pienin = ((Integer)Collections.max(luvut,new LaskevaInt())).intValue();
System.out.println("Pienin = " + pienin); // Pienin = 0
List luvut2 = new LinkedList();
luvut2.addAll(0,luvut);
tulosta(System.out,luvut2); // 0 2 7 22 71 99
luvut2 = luvut.subList(2,5);
tulosta(System.out,luvut2); // 7 22 71
}
}