当前位置: 首页 > 知识库问答 >
问题:

接口、参数化类型和集合

戴原
2023-03-14

这可能是一个Java101问题。但是我已经离开java十年了,所以它对我来说是新的。

而且,changeFurColor()使用实现 的比较器对输入ArrayList进行排序,因此我需要在changeFurColor()方法中使用这个参数化类型。

我用changeFurColor(dogs)调用方法;

但是,这不会编译。类型 与类型 不匹配,尽管前者实现了后者。

伪代码:

public interface AnimalInterface
{
    public Color getColor();
    ......
}

public class Dog implements AnimalInterface
{

}
public class Cat implements AnimalInterface
{

}

public void example()
{
    ArrayList<Dog> dogs = new ArrayList<Dog>();
    ArrayList<Cat> cats = new ArrayList<Cat>();
    ArrayList<Mouse> mice = new ArrayList<Mouse>();
    changeFurColor(dogs)

}

public void changeFurColor(ArrayList <AnimalInterface> list)
{
    ... ..

    Collections.sort(list, MyAnimalFurComparator);

}


public class MyAnimalFurComparator implements Comparator<AnimalInterface>
{

    @Override
    public int compare(AnimalInterface o1, AnimalInterface o2)
    {
        ...
    }
}

更新changeFurColor(dogs)不编译

共有1个答案

史智志
2023-03-14

这是正确的答案(对于跟随我的新手来说)

Solitirios对这个问题的评论功不可没。

public static <T extends AnimalInterface> void changeFurColor(ArrayList<T> list) –
 类似资料:
  • 流接口中的映射函数定义如下: 函数参数列表与函数接口自己的规范一致 方法是 这意味着它需要一个T,但返回一个R。但我正在运行这个代码 奇怪的是,为什么它能工作,但论点类型似乎不匹配?没有简单的方法来解释它,但我的理解是,一个函数应该接受类型T的输入并返回类型R。当它在流中使用时,它接受类型String的输入并返回类型int(即String.length())。但是小溪。map被键入以返回与流相同的

  • 问题内容: 我在弄清楚以下RHS中期望使用什么类型参数时遇到问题 为什么副本不合法? 问题答案: 具体参数化类型的数组固有地被破坏。请记住,数组是协变的,数组类型检查是运行时操作。在运行时,所有泛型都已被擦除,因此Array Store检查无法从中分辨出来。 泛型的基本约定是:“我,编译器,保证如果编写的代码不生成警告,则在运行时永远不会得到类强制转换异常。” 编译器也不能向您保证,如果在数组中放

  • 为什么我不能这样做?我得到编译错误。 那是Java8 我不认为这里违反了任何OO原则。 这真的让我很难实现通用 API...... (我试图将泛型从游戏中剔除,因为泛型API变得反直觉了)

  • 问题内容: 我想了解为什么下面的代码片段无法编译。将函数接受为可能具有任何返回类型的函数参数的Go方法是什么? 播放:https://play.golang.org/p/CqbuEZGy12 我的解决方案基于Volker的答案: 播放:https://play.golang.org/p/waOGBZZwN7 问题答案: 你绊倒了围棋新人一个非常普遍的误解:空接口并 不能 意味着“任何类型”。确实不

  • Interfaces and other types 接口与其它类型 接口 Interfaces in Go provide a way to specify the behavior of an object: if something can do this, then it can be used here. We’ve seen a couple of simple examples al

  • 我定义了这个类: 在其他地方,在具有此签名的函数中: 我尝试返回新的ActorMapper(),但javac抱怨: 我可以投射它,它工作得很好,但为什么不能编译呢。有人能帮我吗?:)