Difference between revisions of "2011-40-Java3"

From Teknologisk videncenter
Jump to: navigation, search
(Created page with "= Opgaver = == Kapitel 12 == === Opgave 3 === ==== Main ==== <source lang="java">package comparator; import java.util.*; public class sorting { public static void main(S...")
 
m
 
Line 5: Line 5:
 
=== Opgave 3 ===
 
=== Opgave 3 ===
  
==== Main ====
+
==== Main ====
  
 
<source lang="java">package comparator;
 
<source lang="java">package comparator;
Line 24: Line 24:
 
         list.add("c#ftw");
 
         list.add("c#ftw");
 
          
 
          
         Collections.sort(list,new NormalComparable());
+
         Collections.sort(list,new AscendingCompare());
 
          
 
          
 
         print(list);
 
         print(list);
 
          
 
          
         Collections.sort(list,new ReverseCompare());
+
         Collections.sort(list,new DescendingCompare());
  
 
         print(list);
 
         print(list);
 
          
 
          
         Collections.sort(list,new SecondCharCompare());
+
         Collections.sort(list,new SecondCharAscendingCompare());
  
 
         print(list);
 
         print(list);

Latest revision as of 08:58, 5 October 2011

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.
    }
}