JuanMan394
JuanMan394

Reputation: 31

Compare method with generics

well this is my problem: I'm using a class ArrayLinearList to create diferent array types. Now, I have to create a boolean method: compare(Linearlist other) and LinearList is an interface for ArrayLinearList.

When I use compare, this method is supossed to return false if the compared elements are different. But I don't know how to do it work, cause the argument other of the element are an Interface, and the array to compare is a T[] array type so when I use the method should look like this: element.compare(other);

So how can I convert a LinearList object, where LinearList is an interface, to an object of t[] type??

public boolean compare(LinearList other){
ArrayLinearList<T> element2 = other;
// cast try:

 Integer size1 = other.size();
 Integer size2 = 0;


 for (int  i = 0; i< size; i++) 
  size2++;

    if (size2 == size1) 
      return true;
        else return false;

//else return false;

}

then I get this error:error: incompatible types: LinearList<CAP#1> cannot be converted to ArrayLinearList<T> ArrayLinearList<T> element2 = other; ^ where T is a type-variable: T extends Comparable<T> declared in class ArrayLinearListTaller1 where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ? 1 error

SO, how can I convert other to a element type T[], or how can I compare them??

If someone can help me, I would be very grateful¡¡¡ :)

Upvotes: 2

Views: 248

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79818

The declaration should be or public boolean compare(LinearList<? extends T> other), so that the compiler knows that the objects that it's retrieving from other will be of type T or a subtype thereof.

Upvotes: 1

Related Questions