0

I have the following interfaces:

public interface CustomWebElement extends WebElement
. . . methods

In the following places, when I try to cast WebElement to CustomWebElement things are fine:

CustomWebElement a = (CustomWebElement) element.findElement(by); //findElement return WebElement

but the calls to findElements method which returns List<WebElement> casting is failing:

List<CustomWebElement> a = (List<CustomWebElement>) element.findElements(by);

giving me exception:

Inconvertable types; Cannot cast List<WebElement> to List<CustomWebElement>

why List cast is failing in this case?

batman
  • 4,728
  • 8
  • 39
  • 45

4 Answers4

3

Please take a look at http://docs.oracle.com/javase/tutorial/java/generics/

CustomWebElement extends WebElement does NOT mean that List<CustomWebElement> extends List<WebElement>

Atul
  • 2,673
  • 2
  • 28
  • 34
1

A List<WebElement> is an object type in its own right as is List<CustomWebElement>, and List<CustomWebElement> does not extend List<WebElement>

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

It is because List<WebElement> is neither a subtype nor supertype of List<CustomWebElement>. For more information, you can read Item25 from Effective Java of Joshua Bloch. I am copying and pasting from his book

Arrays differ from generic types in two important ways. First, arrays are covariant. This scary-sounding word means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, List is neither a subtype nor a supertype of List

Shiva Kumar
  • 3,111
  • 1
  • 26
  • 34
0

Use of wildcards while using generics may help Like

List<? extends WebElement>

Dhan
  • 42
  • 2