gpt4 book ai didi

Java泛型,使用类层次结构时如何避免未经检查的分配警告?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:12 25 4
gpt4 key购买 nike

我想使用一种方法,该方法使用通用参数并在类层次结构上返回通用结果。

编辑: SupressWarnings("unchecked") 允许回答:-)

这是一个示例代码来说明我的问题:

import java.util.*;

public class GenericQuestion {

interface Function<F, R> {R apply(F data);}
static class Fruit {int id; String name; Fruit(int id, String name) {
this.id = id; this.name = name;}
}
static class Apple extends Fruit {
Apple(int id, String type) { super(id, type); }
}
static class Pear extends Fruit {
Pear(int id, String type) { super(id, type); }
}

public static void main(String[] args) {

List<Apple> apples = Arrays.asList(
new Apple(1,"Green"), new Apple(2,"Red")
);
List<Pear> pears = Arrays.asList(
new Pear(1,"Green"), new Pear(2,"Red")
);

Function fruitID = new Function<Fruit, Integer>() {
public Integer apply(Fruit data) {return data.id;}
};

Map<Integer, Apple> appleMap = mapValues(apples, fruitID);
Map<Integer, Pear> pearMap = mapValues(pears, fruitID);
}

public static <K,V> Map<K,V> mapValues(
List<V> values, Function<V,K> function) {

Map<K,V> map = new HashMap<K,V>();
for (V v : values) {
map.put(function.apply(v), v);
}
return map;
}
}

如何从这些调用中删除通用异常:

Map<Integer, Apple> appleMap = mapValues(apples, fruitID);
Map<Integer, Pear> pearMap = mapValues(pears, fruitID);

奖励问题:如果我以这种方式声明 fruitId 函数,如何消除编译错误:

Function<Fruit, Integer> fruitID = new Function<Fruit, Integer>() {public Integer apply(Fruit data) {return data.id;}};

在处理层次结构时,我对泛型非常困惑。任何指向关于 和 的使用的好资源的指针都将不胜感激。

最佳答案

2 个小变化:

public static void main(final String[] args){

// ... snip

// change nr 1: use a generic declaration
final Function<Fruit, Integer> fruitID =
new Function<Fruit, Integer>(){

@Override
public Integer apply(final Fruit data){
return data.id;
}
};

// ... snip
}

public static <K, V> Map<K, V> mapValues(final List<V> values,

// change nr. 2: use <? super V> instead of <V>
final Function<? super V, K> function){

// ... snip
}

作为引用,请阅读:

The get-put principle

关于Java泛型,使用类层次结构时如何避免未经检查的分配警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5309922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com