简体   繁体   中英

Unable to create a class with name Entry

Following code fails compilation with error following error message :

Type mismatch: cannot convert from element type Test1.Entry to Map.Entry

My question is can't we ever use class with name Entry in our project while using hash map ? And why this error is there though i did not import any Entry class here.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Test1 {

    public static class Entry<T> {
        public String m() {
            return "A";
        }
    }

    public static void main(String[] args) {
        final Set<Entry> a = new HashSet<>();

        new HashMap<String, Entry>() {
            {
                for (final Entry entry : a) {
                    put(entry.m(), entry);
                }
            }
        };
    }
}

Is there any way I can keep this class name and code compiles successfully.

You have a issue with the names:

your Entry<T> is shadowing at some point the java.util.Map.Entry<K, V>

just rename the Entry to something else

public static class MyEntry<T> {
    public String m() {
        return "A";
    }
}

You need to tell the compiler that you want to use Entry interface provided by java.util.

As you already have a class named Entry in the same package in which you are using it hence it is implicitly imported. For all the places where you intent to use Entry from java.util you have to explicitly use java.util.Map.Entry instead of just Entry . This way you can use both the classes.

Since you are using double brace initialization the maps internals are exposed in that block.

Either rename the Entry class or move the initialization code out of the init block of the HashMap so your Entry does not shadow the maps internal Entry implementation.

final HashMap<String, Entry> map = new HashMap<>();
for (final Entry entry : a) {
   map.put(entry.m(), entry);
}

This snapshot might clear your doubt,

在此输入图像描述

As error popup states, the compiler is thinking that Inside your for loop it's java.util.Map.Entry but you want to traverse over your custom Entry class over here.

Even though you assume that you aren't importing java.util.Map.Entry , Try removing 1st import (ie HashMap) and you will see that you are no longer getting Incompatible Types Error.

You can try any of the suggested workarounds to get rid of this problem.

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