Joker
Joker

Reputation: 11146

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.

Upvotes: 1

Views: 178

Answers (4)

Bart
Bart

Reputation: 17361

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

Upvotes: 1

Neeraj Jain
Neeraj Jain

Reputation: 7730

This snapshot might clear your doubt,

enter image description here

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 (i.e. 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.

Upvotes: 0

nits.kk
nits.kk

Reputation: 5316

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.

Upvotes: 1

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

Upvotes: 1

Related Questions