为什么选择java Instance初始化器? [英] Why java Instance initializers?

查看:110
本文介绍了为什么选择java Instance初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中Instance Initializers的含义是什么?

我们不能把这段代码放在构造函数的开头吗?

What is the sense of "Instance Initializers" in Java ?
Can't we just put that block of code at the beginning of the constructor instead?

推荐答案

我经常使用它们,通常用于在一个语句中创建和填充Map(而不是使用丑陋的静态块):

I use them very often, typically for creating and populating Map in one statement (rather than using an ugly static block):

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
};

一个有趣且有用的装饰是在一个地方创建一个不可修改的地图声明:

One interesting and useful embellishment to this is creating an unmodifiable map in one statement:

private static final Map<String, String> CODES = 
    Collections.unmodifiableMap(new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
});

比使用静态块和处理最终等的单数赋值方式更整洁。

Way neater than using static blocks and dealing with singular assignments to final etc.

另一个提示:不要害怕创建简化实例块的方法:

And another tip: don't be afraid to create methods too that simplify your instance block:

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("Alpha");
        put("Bravo");
    }

    void put(String code) {
        put(code.substring(0, 1), code);
    }
};

这篇关于为什么选择java Instance初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆