简体   繁体   中英

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.

@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)

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?

Your map method's second argument should be a Function . The expression hashCode() does not result in a Function ; it calls the hashCode method which returns an int . Hence your error is that int is not assignable to Function .

I think you want to call map with a function that computes the hashCode of each string. The simplest way to do that is by passing a method reference to String::hashCode :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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