Java9新特性系列(钻石操作符改进)

Java7前时代

在Java7之前每次声明泛型变量的时必须左右两边都同时声明泛型:

List list = new ArrayList();
Set set = new HashSet();
Map> map = new HashMap>();
复制代码

这样看来右边的泛型声明就变得是多余的了?

Java7

在Java7中,对这一点进行了改进,就不必两边都要声明泛型,这种只适用<>标记的操作,称之为钻石操作符Diamond Operator

List list = new ArrayList<>();
Set set = new HashSet<>();
Map> map = new HashMap<>();
复制代码

对比之前的用法是不是很清晰很方便呢?

但是Java7中钻石操作符不允许在匿名类上使用:

List list = new ArrayList<>();
List list = new ArrayList<>(){};//报错
Set set = new HashSet<>();
Set set = new HashSet<>(){};//报错
Map> map = new HashMap<>();
Map> map = new HashMap<>(){};//报错
复制代码

如果与匿名类共同使用,会报错:'<>' cannot be used with anonymous classes

Java9

在Java9中,钻石操作符能与匿名实现类共同使用,官方Feature给出了如下说明:

Allow diamond with anonymous classes if the argument type of the inferred type is denotable. Because the inferred type using diamond with an anonymous class constructor could be outside of the set of types supported by the signature attribute, using diamond with anonymous classes was disallowed in Java SE 7. As noted in the JSR 334 proposed final draft, it would be possible to ease this restriction if the inferred type was denotable.

List list = new ArrayList<>() {
    @Override
    public int size() {
        return super.size();
    }

    @Override
    public String toString() {
        return super.toString();
    }
};
        
Set set = new HashSet<>() {
    @Override
    public int size() {
        return super.size();
    }
    
    @Override
    public String toString() {
        return super.toString();
    }
};

Map> map = new HashMap<>() {
    @Override
    public int size() {
        return super.size();
    }

    @Override
    public String toString() {
        return super.toString();
    }
};
复制代码

微信公众号: 码上论剑
请关注我的个人技术微信公众号,订阅更多内容

你可能感兴趣的:(Java9新特性系列(钻石操作符改进))