How do I create some variable type alias in Java

Lee picture Lee · Apr 9, 2011 · Viewed 43.4k times · Source

let say I have this code

Map<String, String> list = new HashMap<String, String>();
list.put("number1", "one");
list.put("number2", "two");

how can I make some "alias" the type

Map<String, String>

to something that easier to be rewritten like

// may be something like this
theNewType = HashMap<String, String>;

theNewType list = new theNewType();
list.put("number1", "one");
list.put("number2", "two");

basically my question is, how to create "alias" to some "type", so i can make it easier to write and easier when need to change the whole program code.

Thanks, and sorry if this is silly question. I'm kinda new in Java.

Answer

KARASZI Istv&#225;n picture KARASZI István · Apr 9, 2011

There are no aliases in Java. You can extend the HashMap class with your class like this:

public class TheNewType extends HashMap<String, String> {
    // default constructor
    public TheNewType() {
        super();
    }
    // you need to implement the other constructors if you need
}

But keep in mind that this will be a class it won't be the same as you type HashMap<String, String>