简体   繁体   中英

Cast a list of concrete type to a list of its interfaces in Java

Is there a way to cast a list of concrete types to a list of its interfaces in Java?

For example:

public class Square implements Shape { ... }

public SquareRepository implements Repository {

  private List<Square> squares;

  @Override
  public List<Shape> getShapes() {
    return squares; // how can I return this list of shapes properly cast?
  }

}

Thanks in advance,

Caps

You can make use of the generic wildcards to allow for derived lists to be used as base lists:

public List<? extends Shape> getShapes() { ... }

Note that the returned list cannot have non-null items added to to it . (As Mr. Sauer points out, you can add null and deletion is fine as well.) That's the trade-off, though hopefully that won't matter in your case.

Since getShapes() is an override, you would need to update the return type in Repository as well.

If you really want to do this something like the below might work

@Override
public List<Shape> getShapes() {
   return new ArrayList<Shape>(squares); 
}

If you're in control of the Repository interface, I suggest you refactor it to return something of the type List<? extends Shape> List<? extends Shape> instead.

This compiles fine:

interface Shape { }

class Square implements Shape { }

interface Repository {
    List<? extends Shape> getShapes();
}

class SquareRepository implements Repository {
    private List<Square> squares;

    @Override
    public List<? extends Shape> getShapes() {
        return squares;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM