1 回答

TA貢獻1798條經驗 獲得超7個贊
請注意,問題仍然是為什么您的內部方法使用接口,而公開公開的方法使用具體類。通常情況恰恰相反。如果可能的話,我建議將返回類型更改findAllPaginatedAndSorted為List<? extends IDto>。
您不能從List<? extends IDto>to進行轉換List<FollowingResponseDto>,因為前者可以包含實現的其他類型IDto,而不僅僅是FollowingResponseDto.
想象一下以下場景:
interface I {}
class A implements I {}
class B implements I {}
List<I> interfaceList = ...;
interfaceList.add(new A());
interfaceList.add(new B());
List<A> aList = interfaceList; // error! interfaceList contains a B, and a B is not allowed in a list of As
現在您可能會爭辯說您的場景中沒有B,并且List<? extends IDto>僅包含 的實例FollowingResponseDto。但你的編譯器不知道這一點,也不能保證這在未來的任何時候都不會改變。
要解決此問題,您需要自己進行轉換。要么在中間做一個邪惡的轉換List<?>,要么創建一個新的List<FollowingResponseDto>元素并單獨添加每個元素List<? extends IDto>:
邪惡的:
return (List<FollowingResponseDto>)(List<?>)findPaginatedAndSortedInternal(...);
不邪惡:
var idtoList = findPaginatedAndSortedInternal(...);
var followingResponseDtoList = new ArrayList<FollowingResponseDto>();
for (var idto : idtoList) {
if (idto instanceof FollowingResponseDto)
followingResponseDtoList.add((FollowingResponseDto)idto);
}
return followingResponseDtoList;
添加回答
舉報