How do I create some variable type alias in Java

JavaTypesHashmapAlias

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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>

Solution 2 - Java

There is no typedef equivalent in Java, and there is no common idiom for aliasing types. I suppose you could do something like

class StringMap extends HashMap<String, String> {}

but this is not common and would not be obvious to a program maintainer.

Solution 3 - Java

Although Java doesn't support this, you can use a generics trick to simulate it.

class Test<I extends Integer> {
    <L extends Long> void x(I i, L l) {
        System.out.println(
            i.intValue() + ", " + 
            l.longValue()
        );
    }
}

Source: http://blog.jooq.org/2014/11/03/10-things-you-didnt-know-about-java/

Solution 4 - Java

The closest one could think of is to make a wrapper class like so

class NewType extends HashMap<String, String> {
     public NewType() { }
}

I really wish Java had a sound type aliasing feature.

Solution 5 - Java

Nothing like that exists in Java. You might be able to do something with IDE templates or autocompletion, and look forward to (limited) generics type inference in Java 7.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeeView Question on Stackoverflow
Solution 1 - JavaKARASZI IstvánView Answer on Stackoverflow
Solution 2 - JavaRom1View Answer on Stackoverflow
Solution 3 - JavaAndreyView Answer on Stackoverflow
Solution 4 - JavaIngoView Answer on Stackoverflow
Solution 5 - JavaMichael BorgwardtView Answer on Stackoverflow