我在阅读泛型时遇到了PECS(制片extends人和消费者的super简称).
能否给我一个人解释如何使用佩奇之间解决困惑extends和super?
在尝试理解Spring MVC中的概念之后,我遇到了Collection<? extends Book>我以前从未见过的表达式.我试图自己搞清楚,但我发现使用Collection<? extends Book>和没有区别Collection<Book>.我猜它只允许Book的扩展,但它确实允许Book.抓那个.我曾尝试使用谷歌,但从那以后?是google中的通配符,它几乎不可能搜索.我已经搜索了stackoverflow以获得答案,但所有关于此问题的问题(例如List <?extends MyType>和<?extends> Java语法)已经知道了Collection<? extends T>.这段代码最初引起了我的兴趣:
import java.util.ArrayList;
import java.util.Collection;
public class Book {
public static void main(String[] args) {
BookCase bookCase1 = new BookCase();
BookCase bookCase2 = new BookCase(bookCase1);
}
}
class BookCase extends ArrayList<Book> {
public BookCase() {
}
//acts same as public BookCase(Collection<Book> c) {
public BookCase(Collection<? extends Book> c) {
super(c);
}
}
Run Code Online (Sandbox Code Playgroud)
怎么<? extends T> …
我正在尝试开发一个通用的表加载器,该模式在运行时是已知的.这需要具有包含不同类型的元素的列表,并支持各种get和诸如设置方法的类getInt(int index),asString(int index),asStringList(int index).元素我考虑的类型有Integer,Double,String,和List<Integer>,List<Double>和List<String>.每个元素的实际类型在运行时是已知的,我将它们存储在描述其模式的List中以供进一步处理.
我的问题是:我应该将这些元素列表存储在List<Object>或中List<? extends Object>吗?还是有更好的方法来实现这样的课程?
我在我的项目中使用ExpandableRecyclerView来嵌套RecyclerView.它工作得很好,除非您需要动态更新父列表.
我的项目将Product类作为父对象(并扩展ParentListItem).我从API获取产品列表,因此需要清除当前列表并添加我有的列表.
在ExpandableRecyclerAdapter中我试过这个方法 -
public void onDataChanged(ArrayList<Product> parentObjects) {
this.getParentItemList().clear();
this.getParentItemList().addAll(parentObjects);
this.notifyItemRangeChanged(0, parentObjects.size() - 1);
}
Run Code Online (Sandbox Code Playgroud)
然而,它给出了一个奇怪的通用错误
Error:(60, 33) error: no suitable method found for addAll(ArrayList<Product>)
method List.addAll(Collection<? extends CAP#1>) is not applicable
(actual argument ArrayList<Product> cannot be converted to Collection<? extends CAP#1> by method invocation conversion)
method List.addAll(int,Collection<? extends CAP#1>) is not applicable
(actual and formal argument lists differ in length)
method Collection.addAll(Collection<? extends CAP#1>) is not applicable
(actual argument ArrayList<Product> cannot be …Run Code Online (Sandbox Code Playgroud) generics android android-recyclerview expandablerecyclerview
ArrayList<? extends A> array = new ArrayList<A>();
array.add(new A());
Run Code Online (Sandbox Code Playgroud)
为什么这不编译?