我们说我有以下课程:
Animal是基类,cat,dog和cow的每个子类.
我现在有一个Set<Cat>,Set<Dog>并且Set<Cow>每个都以相同的方式使用,因此有必要制作一个通用函数来对它们进行操作:
private boolean addObject(Animal toAdd, Animal defVal, Set<? extends Animal> vals)
Run Code Online (Sandbox Code Playgroud)
这很好用,我可以自由地传递我的套装没有问题.
出现问题:我无法尝试将Animal toAdd添加到参数val.谷歌搜索显示,如果我改变方法阅读:
private boolean addObject(Animal toAdd, Animal defVal, Set<? super Animal> vals)
Run Code Online (Sandbox Code Playgroud)
我将能够将Animal添加到参数val.这是有效的,除了现在,我不能通过我的子集我的猫,狗和奶牛.进一步的研究告诉我,以下工作,没有警告启动:
private <T> boolean addObject(T toAdd, T defVal, Set<? super T> vals)
Run Code Online (Sandbox Code Playgroud)
问题是,我需要能够执行Animal所有的方法调用.使用简单的强制转换很容易解决这个问题:
((Animal)toAdd).getAnimalType()
Run Code Online (Sandbox Code Playgroud)
有没有解决这个问题的方法所以我可以保留通用功能,而不需要转换?除了使我的集合所有基本类型集合,动物在这个例子的情况下?
我有一个奇怪的(在我看来)问题.我正在为自定义渲染器我需要的一些自定义功能制作一个自定义JComboBoxModel我还不确定如何处理,我稍后会发布.
无论如何,正如标题所示我得到了一些类型错误.
这是类(当前)代码:
package miscclasses;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
public class CustomComboBoxModel<String> extends AbstractListModel<String> {
/**
* Contains a list of row indexes that shouldn't be displayed.
*/
private ArrayList<String> alreadySelectedIndexes;
/**
* The comboBoxes selected index.
*/
private int selectedIndex=-1;
/**
* Contains a list of values in this model.
*/
private ArrayList<String> vals;
/**
* Creates an empty CustomComboBoxModel.
*/
public CustomComboBoxModel() {
this.alreadySelectedIndexes=new ArrayList<>();
this.vals = new ArrayList<>();
}
/**Creates a CustomComboBoxModel with the values passed in. …Run Code Online (Sandbox Code Playgroud)