2015-04-27 6 views
5

Attualmente sto ottenendo un errore quando si tenta di ordinare questi oggetti Pet in base al peso. Sono sicuro che sia qualcosa di semplice, ma non riesco a capire perché questo confronto non funzioni.ArrayList ordinamento oggetti usando Comparator

Error: The return type is incompatible with java.util.Comparator.compare(Pet, Pet)

ArrayListNoDups classe classe

import java.util.*; 
import java.util.Collections; 
import java.util.Comparator; 
import java.lang.Object; 

public class ArrayListNoDups { 
    public static void main(String[] args) { 
     ArrayList<Pet> list = new ArrayList<Pet>(); 
     String name; 
     Integer age; 
     Double weight; 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("If you wish to stop adding Pets to the list, please put a 0 for all 3 fields."); 

     do { 
      System.out.println("Enter a String for Pet name: "); 
      name = keyboard.next(); 
      System.out.println("Enter an int for Pet age: "); 
      age = keyboard.nextInt(); 
      System.out.println("Enter a double for Pet weight: "); 
      weight = keyboard.nextDouble(); 

      if (name.length() > 0 && age > 0 && weight > 0) 
       list.add(new Pet(name, age, weight)); 
     } while (name.length() > 0 && age > 0 && weight > 0); 

     System.out.println("Your list sorted by WEIGHT ========================= "); 
     Collections.sort(list, Pet.SortByWeight); 
     for (Pet p2 : list) 
      p2.writeOutput(); 

    } 
} 

Pet

import java.util.*; 

public class Pet { 
    private String name; 
    private Integer age; // in years 
    private double weight; // in pounds 

    public void writeOutput() { 
     System.out.println("Name: " + name); 
     System.out.println("Age: " + age + " years"); 
     System.out.println("Weight: " + weight + " pounds"); 
    } 

    public void set(String newName) { 
     name = newName; 
     // age and weight are unchanged. 
    } 

    public void set(int newAge) { 
     if (newAge <= 0) { 
      System.out.println("Error: illegal age."); 
      System.exit(0); 
     } else 
      age = newAge; 
     // name and weight are unchanged. 
    } 

    public void set(double newWeight) { 
     if (newWeight <= 0) { 
      System.out.println("Error: illegal weight."); 
      System.exit(0); 
     } else 
      weight = newWeight; 
     // name and age are unchanged. 
    } 

    public Pet(String name, int age, double weight) { 
     this.name = name; 
     this.age = age; 
     this.weight = weight; 
    } 

    public String getName() { 
     return name; 
    } 

    public int getAge() { 
     return age; 
    } 

    public double getWeight() { 
     return weight; 
    } 

    public static Comparator<Pet> SortByWeight = new Comparator<Pet>() { 
     public double compare(Pet pet1, Pet pet2) { 
      return pet1.getWeight() - pet2.getWeight(); 
     } 
    }; 
} 

risposta

7

compare metodo Comparator interfaccia restituisce un int, non double.

Cambio:

public double compare(Pet pet1, Pet pet2) 

a:

public int compare(Pet pet1, Pet pet2) 

Il comparatore può apparire come segue:

public static Comparator<Pet> SortByWeight = new Comparator<Pet>() { 
    public int compare(Pet pet1, Pet pet2) { 
     return (int)(pet1.getWeight() - pet2.getWeight()); 
    } 
}; 
+1

@MartDellon appena lanciato la differenza in int - 'ritorno (int) (pet1.getWeight() - pet2.getWeight());' – Eran

+0

Per la visibilità, questo funziona altrettanto bene come risposta di Ankit. Ho appena provato il suo primo. Grazie a entrambi per l'aiuto! – JoshTheGray

+1

@MartDellon Si noti che se si utilizza la soluzione Ankit, ogni confronto comporterà la creazione di due oggetti Double che sarebbero immediatamente idonei per la garbage collection. Un algoritmo di ordinamento decente di n elementi richiede confronti in n * log (n), il che significa che creerai 2 * n * log (n) Doppie objcets e darai lavoro extra al garbage collector. Questo probabilmente renderà l'ordinamento più lento della mia soluzione, che funziona su tipi primitivi e non crea alcun oggetto. – Eran

0

Il problema è compare necessità di restituire un numero intero per conformarsi a tale Comparator interfaccia.

È possibile eseguire il downward su un int nel confronto, o forse meglio, utilizzare solo Double.compare().

Nota a margine: l'uso dell'annotazione @Override in queste situazioni (l'implementazione di interfacce comuni) farà in modo che il compilatore aiuti a vedere prima questi problemi.

0

Prova questo:

public int compare(Pet pet1, Pet pet2) { 
      return new Double(pet1.getWeight()).compareTo(new Double(pet2.getWeight())); 
     } 
+0

Questo ha funzionato magnificamente. Grazie! – JoshTheGray

+0

puoi accettare la risposta se risolvono il tuo problema. :) –