Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中创建一些变量类型别名_Java_Types_Hashmap_Alias - Fatal编程技术网

如何在Java中创建一些变量类型别名

如何在Java中创建一些变量类型别名,java,types,hashmap,alias,Java,Types,Hashmap,Alias,假设我有这个代码 Map<String, String> list = new HashMap<String, String>(); list.put("number1", "one"); list.put("number2", "two"); Map list=newhashmap(); 列表。放置(“编号1”、“一”); 列表。放置(“第二”、“第二”); 我如何才能使一些“别名”的类型 Map 更容易重写的东西,比如 // may be something l

假设我有这个代码

Map<String, String> list = new HashMap<String, String>();
list.put("number1", "one");
list.put("number2", "two");
Map list=newhashmap();
列表。放置(“编号1”、“一”);
列表。放置(“第二”、“第二”);
我如何才能使一些“别名”的类型

Map
更容易重写的东西,比如

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

theNewType list = new theNewType();
list.put("number1", "one");
list.put("number2", "two");
//可能是这样的
newtype=HashMap;
theNewType list=新建theNewType();
列表。放置(“编号1”、“一”);
列表。放置(“第二”、“第二”);
基本上,我的问题是,如何为某个“类型”创建“别名”,以便在需要更改整个程序代码时更易于编写


谢谢,如果这是个愚蠢的问题,我很抱歉。我对Java有点陌生。

Java中没有类似的东西。您可能可以使用IDE模板或自动完成来做一些事情,并期待使用Java 7(有限)。

Java中没有别名。您可以使用您的类扩展
HashMap
类,如下所示:

public class TheNewType extends HashMap<String, String> {
    // default constructor
    public TheNewType() {
        super();
    }
    // you need to implement the other constructors if you need
}
public类newtype扩展HashMap{
//默认构造函数
public TheNewType(){
超级();
}
//如果需要,您需要实现其他构造函数
}

但是请记住,这将是一个类,它与您键入的HashMap不同,Java中没有等价的类型定义,也没有用于别名类型的通用习惯用法。我想你可以这样做

class StringMap extends HashMap<String, String> {}
class StringMap扩展HashMap{}

但是这并不常见,对于程序维护人员来说也不明显。

最接近的方法就是这样创建一个包装类

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

我真希望Java有一个声音类型别名功能。

尽管Java不支持这个功能,但您可以使用泛型技巧来模拟它

class Test<I extends Integer> {
    <L extends Long> void x(I i, L l) {
        System.out.println(
            i.intValue() + ", " + 
            l.longValue()
        );
    }
}
类测试{
无效x(I,L){
System.out.println(
i、 intValue()+“,”+
l、 longValue()
);
}
}

来源:

@Lee-KARASZI István关于类型的警告很重要-请看,泛型有一种替代的技巧/技巧:但因为这是一种更一般类型的专门化,您不能使用
newtype
来代替
HashMap
,正如您不能在返回
Map
时使用后者一样。请记住,如果您这样做,您应该为您的子类实现缺少的序列化接口细节。否则,如果您遇到需要(反)序列化对象的情况,您可能会遇到一些奇怪的情况。我不知道您到底为什么讨厌OP,并希望他被同事揍死。这与其他答案中的想法相同,因为您使用派生的概念来获得一个新的类型名。这里是通过约束类型变量从
Integer
得到的
I
和从
Long
得到的
L
,其他答案通过构造一个新类提出了
NewType
HashMap
。类型变量方法的缺点是只能在类型变量的范围内使用,例如
Test
类或
x
方法。
class Test<I extends Integer> {
    <L extends Long> void x(I i, L l) {
        System.out.println(
            i.intValue() + ", " + 
            l.longValue()
        );
    }
}