How do I create some variable type alias in Java

后端 未结 5 1603
自闭症患者
自闭症患者 2020-12-03 09:12

let say I have this code

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


        
相关标签:
5条回答
  • 2020-12-03 09:57

    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.

    0 讨论(0)
  • 2020-12-03 10:03

    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.

    0 讨论(0)
  • 2020-12-03 10:08

    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.

    0 讨论(0)
  • 2020-12-03 10:12

    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/

    0 讨论(0)
  • 2020-12-03 10:15

    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>

    0 讨论(0)
提交回复
热议问题