Andy Ho
Andy Ho

Reputation: 179

Java Generic Misbound

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;

public interface Comparable<T> {

int compareTo(T other);

}

public class Joueur implements Comparable<Joueur> {

private int points;
private int idJoueur;

public Joueur(int aIdJoueur, int aPoints)
{
    points= aPoints;
    idJoueur = aIdJoueur;
}

public Joueur(int aIdJoueur, int aPoints)
{
    points= aPoints;
    idJoueur = aIdJoueur;
}

public int getIdJoueur()
{
    return idJoueur;
}

public int compareTo(Joueur autre) {
    // TODO Auto-generated method stub
    if (points < autre.points) return -1;
    if (points > autre.points) return 1;
    return 0;
}

public class CollectionJoueur {

ArrayList<Joueur> j = new ArrayList<Joueur>();

public CollectionJoueur(int aIdJoueur, int aPoints)
{
    Joueur ajouterJ = new Joueur(aIdJoueur, aPoints);
    ajouter(ajouterJ);
}
public void ajouter(Joueur joueur)
{
    j.add(joueur);
}

public iterateurJoueur creerIterateur()
{
    Collections.sort(j);

    Iterator<Joueur> itrJoueur = j.iterator();
    while(itrJoueur.hasNext())
    {

    }
}

}

So here's my problem, I have been trying to do comparable sort, but in the collections sort it gave me an error of generic misbound. I have a class collection to put the player into the arraylist then i have to sort them out in ascending order.

Upvotes: 0

Views: 57

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

You'll notice that Collections.sort(..) is defined as

public static <T extends Comparable<? super T>> void sort(List<T> list) {

In other words, it expects a type that is a sub type of java.lang.Comparable. Your class is not a sub type of java.lang.Comparable. What you are trying to do with Collections.sort(..) is not possible.

Get rid of your Comparable type and use java.lang.Comparable.

Or write your own sorting method.

Upvotes: 1

Andres
Andres

Reputation: 10717

You should implement java.lang.Comparable interface, not your own Comparable interface.

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

Upvotes: 5

Related Questions