简体   繁体   中英

Sorting ascending with list

I am practicing with comparators and interfaces and I have quite a hard time with it. I am trying to make a boolean method that returns true if the List is in ascending order.

But for some reason I get an error if I use Collections.sort .

What exactly am I missing in my code and why isn't it working?

Here is the code:

Constructor

public class Stijgen implements RijtjesControle{

private int nummer;

public Stijgen(int nummer) {
    this.nummer = nummer;
}

public int getNummer() {
    return nummer;
}

The main

public static void main(String[] args) {
    List<Stijgen> rijtje = new ArrayList<Stijgen>();
    rijtje.add(new Stijgen(4){});
    rijtje.add(new Stijgen(7){});
    rijtje.add(new Stijgen(1){});
    rijtje.add(new Stijgen(9){});
    rijtje.add(new Stijgen(3){});

    System.out.println("Eerst de getallen op een rijtje zoals het nu is:");
    for (Stijgen rijtje1 : rijtje) {
        System.out.println(rijtje1.getNummer());
    }  
    System.out.println("Nu gesorteed op stijgende volgorde");
    Collections.sort(rijtje);
    for (Stijgen rijtje1 : rijtje) {
        System.out.println(rijtje1);
    }
}

@Override
public <Stijgen extends Comparable<Stijgen>> boolean isStijgend(List<Stijgen> rijtje) {
 Iterator<Stijgen> iter = rijtje.iterator();
 if(!iter.hasNext()){
     return true;
 }
 Stijgen stijgen = iter.next();
 while(iter.hasNext()){
      Stijgen stijgen1 = iter.next();
      if(stijgen.compareTo(stijgen1) > 0){
         return false;
      }
      stijgen = stijgen1;
 }
    return true;
}
}

you can't use java.util.Collections.sort(List) when Stijgen doens't implement the interface Comparable, unless you use the sort method with has a Comparator for Stijgen as a second parameter: java.util.Collections.sort(List, Comparator)

// copy of rijtje
List<Stijgen> sorted = new ArrayList<Stijgen>(rijtje);
// sort copy by comparator
// JAVA8: Collections.sort(sorted, (a, b) -> a.getNummer() - b.getNummer()); 
Collections.sort(sorted, new Comparator<Stijgen>() {
@Override
public int compare(Stijgen a, Stijgen b) {
return a.getNummer() - b.getNummer();
}
});
// check if rijtje is sorted
System.out.println(rijtje.equals(sorted)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM