I need to create a custom class that extends java.util.LinkedHashMap and takes String as key and String as value and has a no-arg constructor that pre-populates this map with initial values.
I am stuck at the first task – how to extend the LinkedHashMap in such a way that instead of generic arguments it accepts only?
I tried this, (not working)
import java.util.LinkedHashMap;
@SuppressWarnings("serial")
public class MyMenu<String, String> extends LinkedHashMap<String, String> {
public MyMenu(){
this.put("index.jsp", "Home Page");
}
}
All you need is:
Remove
<String, String>from your class name and it will work. You are creating a class which is extendingLinkedHashMap<String, String>so your class is already aMapwhich takesStringas a key andStringas a value. If you want to create your own generic class then you have to do like this:Create a class for e.g.:
and then extend that class:
In that case you will have to specify the key and value for your class in order for
SomeMyMenuclass use the key and value asString. You can read more about generics here.But more efficient way to do what you want is to create some final class and declare the map in it like this:
And to get the values from your map use: