001 import java.util.ArrayList;
002 import java.util.Vector;
003 import java.util.LinkedList;
004 import java.util.Iterator;
005 import java.util.Collection;
006 import java.util.Collections;
007 import java.util.Comparator;
008 import java.util.List;
009 import java.io.*;
010 import fi.jyu.mit.ohj2.*;
011
012 /**
013 * Esimerkki Javan algoritmien käytöstä
014 * @author Vesa Lappalainen
015 * @version 1.0, 05.03.2002
016 */
017
018 public class AlgoritmiMalli {
019
020 /**
021 * Luokka joka vertailee kahta kokonaislukuoliota ja
022 * palauttaa niiden järjestyksen niin, että lajittelu menee
023 * laskevaan järjestykseen.
024 */
025 public static class LaskevaInt implements Comparator {
026 public int compare(Object o1, Object o2) {
027 return ((Integer)o2).intValue() - ((Integer)o1).intValue();
028 }
029 }
030
031 public static void tulosta(OutputStream os, Collection luvut) {
032 PrintStream out = Tiedosto.getPrintStream(os);
033 for (Iterator i = luvut.iterator(); i.hasNext(); ) {
034 int luku = ((Integer)i.next()).intValue();
035 out.print(luku + " ");
036 }
037 out.println();
038 }
039
040
041 public static void main(String[] args) {
042 ArrayList luvut = new ArrayList();
043 try {
044 luvut.add(new Integer(0)); luvut.add(new Integer(2));
045 luvut.add(new Integer(99)); luvut.add(new Integer(7));
046 luvut.add(new Integer(22)); luvut.add(new Integer(71));
047 } catch ( Exception e ) {
048 System.out.println("Virhe: " + e.getMessage());
049 }
050 System.out.println(luvut); // [0, 2, 99, 7, 22, 71]
051
052 Collections.sort(luvut);
053 tulosta(System.out,luvut); // 0 2 7 22 71 99
054 Collections.sort(luvut,new LaskevaInt());
055 tulosta(System.out,luvut); // 99 71 22 7 2 0
056 Collections.shuffle(luvut);
057 tulosta(System.out,luvut); // 99 2 7 71 0 22
058 Collections.sort(luvut,Collections.reverseOrder());
059 tulosta(System.out,luvut); // 99 71 22 7 2 0
060 Collections.reverse(luvut);
061 tulosta(System.out,luvut); // 0 2 7 22 71 99
062
063 int suurin = ((Integer)Collections.max(luvut)).intValue();
064 System.out.println("Suurin = " + suurin); // Suurin = 99
065 int pienin = ((Integer)Collections.min(luvut)).intValue();
066 System.out.println("Pienin = " + pienin); // Pienin = 0
067 pienin = ((Integer)Collections.max(luvut,new LaskevaInt())).intValue();
068 System.out.println("Pienin = " + pienin); // Pienin = 0
069
070 List luvut2 = new LinkedList();
071 luvut2.addAll(0,luvut);
072 tulosta(System.out,luvut2); // 0 2 7 22 71 99
073 luvut2 = luvut.subList(2,5);
074 tulosta(System.out,luvut2); // 7 22 71
075
076 }
077 }