[英]Why doesn't this test work for my map function as written?
我被要求在下面為我的地圖功能創建一個測試。
static <U,V> List<V> map(Iterable<U> l, Function<U,V> f) {
List<V> hashes = new ArrayList<>();
for(U x : l) {
V y = f.apply(x);
hashes.add(y);
}
return hashes;
}
我編寫的測試采用一個字符串列表並創建一個哈希列表,將映射的哈希與 api hashCode() 函數的哈希進行比較。
@Test
public void testMap() {
List<String> names = List.of("Mary", "Isla", "Sam");
List<Integer> hashes = fp.map(names, hashCode());
List<Integer> hashesComp = new ArrayList<>();
for (String name : names) {
int hash = name.hashCode();
hashesComp.add(hash);
}
Assertions.assertEquals(hashesComp, hashes);
}
這部分(在 Eclipse 中)
List<Integer> hashes = fp.map(names, hashCode());
給我一個錯誤:
The method map(Iterable<U>,
Function<U,V>) in the type fp is
not applicable for the arguments
(List<String>, int
我究竟做錯了什么? List 不是可迭代的,泛型應該采用我正在使用的類型嗎?
您的map
方法的第二個參數應該是Function
。 表達式hashCode()
不會產生Function
; 它調用返回int
的hashCode
方法。 因此,您的錯誤是int
不可分配給Function
。
我想你想用一個計算每個字符串的 hashCode 的函數來調用map
。 最簡單的方法是將方法引用傳遞給String::hashCode
:
List<Integer> hashes = fp.map(names, String::hashCode);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.