I am trying to sort a List of coordinates. It gives me this error:
error: no suitable method found for sort(List) Collections.sort(vertices); ^ method Collections.<T#1>sort(List<T#1>) is not applicable (inference variable T#1 has incompatible bounds equality constraints: Coordenada lower bounds: Comparable<? super T#1>) method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable (cannot infer type-variable(s) T#2 (actual and formal argument lists differ in length)) where T#1,T#2 are type-variables: T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>) T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>) 1 error
Here is my code:
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PoligonoIrreg{
List<Coordenada> vertices = new ArrayList<Coordenada>();
public PoligonoIrreg(){
}
public void anadeVertice(Coordenada c1){
vertices.add(c1);
}
public void ordenaVertices (){
Collections.sort(vertices);
}
@Override
public String toString( ) {
vertices.forEach((vertice) -> {
System.out.println(vertice);
});
return "Total de vertices: " vertices.size();
}
}
public class Coordenada {
private double x, y, magnitud;
public Coordenada(){
}
public Coordenada(double x, double y) {
this.x = x;
this.y = y;
setMagnitud();
}
//Metodo getter de x
public double abcisa( ) { return x; }
//Metodo getter de y
public double ordenada( ) { return y; }
public double getMagnitud() {
return magnitud;
}
public void setX(double x) {
this.x = x;
setMagnitud();
}
public void setY(double y) {
this.y = y;
setMagnitud();
}
//Sobreescritura del método de la superclase objeto para imprimir con System.out.println( )
@Override
public String toString( ) {
return "Coordenada[" x "," y "] Magnitud:" magnitud;
}
private void setMagnitud(){
magnitud = Math.sqrt((x * x) (y * y));
}
}
Why do I get the error above?
CodePudding user response:
Your Coordenada
class needs to implement the Comparable
interface, otherwise, the sort
method doesn't know how to sort the elements. This means it will need to be declared like
public class Coordenada implements Comparable<Coordenada>
and contain a method
public int compareTo(Coordenada other)
whose return value is negative or positive depending on whether the current object should be sorted before or after the other
object; or zero if the two objects are equal.
CodePudding user response:
Your class should implement Comparable interface and provide implementation to compareTo method.
You can also create a custom comparator to sort the list
Refer this link for more details: https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/