2011-40-Java3

From Teknologisk videncenter
Revision as of 08:58, 5 October 2011 by Utte (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Opgaver

Kapitel 12

Opgave 3

Main

package comparator;

import java.util.*;
public class sorting {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("tiktak");
        list.add("egern");
        list.add("kæmpeegern");
        list.add("somebodywashere");
        list.add("wtf");
        list.add("java");
        list.add("træls");
        list.add("kurt");
        list.add("green");
        list.add("c#ftw");
        
        Collections.sort(list,new AscendingCompare());
        
        print(list);
        
        Collections.sort(list,new DescendingCompare());

        print(list);
        
        Collections.sort(list,new SecondCharAscendingCompare());

        print(list);
        
    }
    
    public static void print(ArrayList list)
    {
        for(Object str : list)
        {
            System.out.println(str.toString());
        }
    }
}

Ascending Compare

package comparator;

import java.util.*;

public class AscendingCompare implements Comparator<String>
{
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2); //Her sammenligner vi o1 med o2.
    }
}

Descending Compare

package comparator;

import java.util.*;

public class DescendingCompare implements Comparator<String>
{
    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1); //Her gør vi det omvendt. o2 sammenligner vi med o1.
    }
}
 

SecondCharAscendingCompare

package comparator;

import java.util.*;

public class SecondCharAscendingCompare implements Comparator<String>
{
    @Override
    public int compare(String o1, String o2) {
        return o1.charAt(1) - o2.charAt(1); //Her tager vi 2nd tegn og bruger char værdien.
    }
}