How to extend HashMap to allow String, String types

I need to create a custom class that extends java.util.LinkedHashMap and takes String as a key and String as a value and has a no-arg constructor that pre-populates this map with initial values.

I am stuck in the first task - how to extend LinkedHashMap in such a way that instead of general arguments it only accepts?

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"); } } 
+8
java hashmap
source share
6 answers

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 create a class that extends 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, you need to do the following:

Create a class, for example:

 public class MyMenu<K, V> { ... } 

and then continue with this class:

 public class SomeMyMenu extends MyMenu<String, String> { ... } 

In this case, you will need to specify the key and value for your class so that the SomeMyMenu class uses the key and value as String . You can find out more about generics here .

But a more efficient way to do what you want is to create some kind of final class and declare a map in it as follows:

 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"); 
+8
source share

If your fight, as you described, is just with an ad, I would try something like:

 class MyCustomizedMap extends LinkedHashMap<String, String> { //... } 
+2
source share

You can do something like below:

  public class MyMap extends LinkedHashMap<String,String>{ 
+2
source share

Try:

 public class MyMap extends LinkedHashMap<String, String> { ... } 
+1
source share

As long as you use JDK 1.5 or higher, you can use generics and create a LinkedHashMap that stores string keys and String values, and initialize it as follows:

 LinkedHashMap<String, String> myMap = new LinkedHashMap<String, String>() { { put("abc", "xyz"); ... }; } 
+1
source share

Composition is a better solution than inheritance in your case:

 class MyProperties implements Map<String, String> { private Map<String, String> delegatee = new LinkedHashMap<String, String>(); // ... delegate your methods to delegatee } 
+1
source share

All Articles