在Java中初始化Hashtables? [英] Initializing Hashtables in Java?

查看:154
本文介绍了在Java中初始化Hashtables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,您可以使用以下代码初始化Hashtables(以及许多其他类型的对象) -

In C# you can initialize Hashtables (and many other types of objects) using code like this -

Hashtable table = new Hashtable {{1, 1}, {2, 2}};

在Java中是否有这样的东西,或者您必须先声明Hashtable然后手动放入其中的项目是一个接一个?

Is there anything like this in Java or do you have to just declare the Hashtable first and then manually put items in it one by one?

推荐答案

这在其他地方得到解答但你可以使用匿名子类:

This is answered elsewhere but you can use an anonymous subclass:

new HashMap<Integer, Integer>() {{ put(1, 1); put(2, 2); }};

很多锅炉板,但仍然是单线:)。不幸的是,这也会抱怨缺少serialVersionUID常量,您可以添加或忽略警告。

Lot's of boiler plate, but still a one-liner :). This will, unfortunately, also complain about the missing serialVersionUID constant which you can either add or ignore the warning on.

这称为实例初始化程序块,更多信息这里

This is called an instance initializer block, more information here.

这篇关于在Java中初始化Hashtables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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