Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extends HashMap to allow String, String types

Tags:

java

hashmap

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");
    }
}
like image 863
Wil Avatar asked Nov 05 '12 15:11

Wil


People also ask

Can HashMap have string as key?

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.

Can we add different data types in HashMap?

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.

Can we extend HashMap?

A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class.


1 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 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");
like image 53
Paulius Matulionis Avatar answered Oct 11 '22 22:10

Paulius Matulionis