简体   繁体   English

为什么这个测试对我写的地图函数不起作用?

[英]Why doesn't this test work for my map function as written?

I am asked to create a test for my map function below.我被要求在下面为我的地图功能创建一个测试。

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;
}

The test I wrote takes a List of Strings and creates a List of Hashes that compares the mapped hashes to hashes of the api hashCode() function.我编写的测试采用一个字符串列表并创建一个哈希列表,将映射的哈希与 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);
    }

This portion (in Eclipse)这部分(在 Eclipse 中)

List<Integer> hashes = fp.map(names, hashCode());

gives me an error:给我一个错误:

The method map(Iterable<U>, 
 Function<U,V>) in the type fp is 
 not applicable for the arguments 
 (List<String>, int  

What am I doing wrong?我究竟做错了什么? Isn't List an iterable and generics should take in the types I'm using? List 不是可迭代的,泛型应该采用我正在使用的类型吗?

Your map method's second argument should be a Function .您的map方法的第二个参数应该是Function The expression hashCode() does not result in a Function ;表达式hashCode()不会产生Function it calls the hashCode method which returns an int .它调用返回inthashCode方法。 Hence your error is that int is not assignable to Function .因此,您的错误是int不可分配给Function

I think you want to call map with a function that computes the hashCode of each string.我想你想用一个计算每个字符串的 hashCode 的函数来调用map The simplest way to do that is by passing a method reference to String::hashCode :最简单的方法是将方法引用传递给String::hashCode

List<Integer> hashes = fp.map(names, String::hashCode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM