Search code examples
javagenericstype-constraints

Type mismatch of same type


I'm currently trying to start on a project for one of my CS courses, and I didn't even get five minutes in before I was hit with a rather perplexing error. My code is as follows:

import java.util.Comparator;
import java.util.List;

public class MergeSorter<T extends Comparable<T>> implements IMergeSorter
{
    private List<T> arrayStore;
    private List<T> temp;
    private int arrSize;

    @Override
    public <T extends Comparable<T>> int sort(List<T> list) 
    {
        arrayStore = list;
        return 0;
    }

The issue i'm having is with the first line in the sort method,

arrayStore = list;

with Eclipse giving me the following error:

Type mismatch: cannot convert from List<T extends Comparable<T>> to List<T extends Comparable<T>>

Notes: The method itself was provided to me by my professor, and the only things I have done with this class are add the three variables at the top, change the class' generic type (it was originally (T), which I changed to (T extends Comparable(T)), and add the one line in the "sort" method. Any help is greatly appreciated!


Solution

  • By having the <T extends Comparable<T>> type declaration in the method signature, you're introducing a second type variable T which, although it has the same name, is not the same as the one in your class declaration.

    To fix, remove the type declaration from your method signature:

    public int sort(List<T> list) 
    {
        arrayStore = list;
        return 0;
    }