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");
}
}
String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.
In this case, we can only put String and Integer data as key-value pairs into the map numberByName. That's good, as it ensures type safety. For example, if we attempt to put a Float object into the Map, we'll get the “incompatible types” compilation error.
A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class.
All you need is:
import java.util.LinkedHashMap;
@SuppressWarnings("serial")
public class MyMenu extends LinkedHashMap<String, String> {
public MyMenu(){
this.put("index.jsp", "Home Page");
}
}
Remove <String, String>
from your class name and it will work. You are creating a class which is extending LinkedHashMap<String, String>
so your class is already a Map
which takes String
as a key and String
as a value. If you want to create your own generic class then you have to do like this:
Create a class for e.g.:
public class MyMenu<K, V> { ... }
and then extend that class:
public class SomeMyMenu extends MyMenu<String, String> { ... }
In that case you will have to specify the key and value for your class in order for SomeMyMenu
class use the key and value as String
. 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:
public static final LinkedHashMap<String, String> MAP = new LinkedHashMap<String, String>() {{
put("index.jsp", "Home Page");
}};
And to get the values from your map use:
SomeClass.MAP.get("Some Key");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With