Search code examples
javagenericsarrayliststaticcomparable

Trying to constrain to the upperbound of the Number class without implementing Comparable for the entire class


I'm trying to make it so that my class is only constrained to the upperbound Number. However, when I try to do a toString() method to get the smallest and largest values, I get the following message:

The method largest(ArrayList<T extends Comparable<T>>) in the type MyList is not applicable for the arguments (ArrayList<T extends Number>)

package p07;

import java.util.ArrayList;

public class MyList<T extends Number>
{
    private ArrayList<T> l;

    public MyList(ArrayList<T> l)
    {
        this.l=l;
    }
    public void add(T x)
    {
        l.add(x);
    }
    public static <T extends Comparable<T> > T smallest(ArrayList<T> l)
    {
        T lowest=l.get(0);
        for(T index:l)
        {
            if(index.compareTo(lowest)<0)
            {
                lowest=index;
            }

        }
        return lowest;

    }
    public static <T extends Comparable<T> > T largest(ArrayList<T> l)
    {
        T largest=l.get(0);
        for(T index:l)
        {
            if(index.compareTo(largest)>0)
            {
                largest=index;
            }

        }
        return largest;

    }
    public final String toString()
    {
        String str;
        str="\nThe list is: ";
        str+="\n"+l.toString();
        str+="\nThe largest value is "+MyList.largest(l);
        str+="\nThe smallest value is "+MyList.smallest(l);
        return str;
    }

}

Is there any way for me to keep my class constrained to the upper bound of the Numbers class without having to implement the Comparable interface for the entire class? I have a feeling the error is occurring because my methods are static, but I'm not sure. I only want to use Comparable for

smallest()

and

largest()

Solution

  • This should work --

    public class MyList< T extends Number & Comparable<? super T> >
    
        public static <T extends Comparable<? super T> > T smallest(ArrayList<T> l)
    
        public static <T extends Comparable<? super T> > T largest(ArrayList<T> l)
    

    You may also remove all the ? super part; it should work fine without wildcards.