【发布时间】:2013-01-22 12:05:39
【问题描述】:
我想创建一个 map,其中包含由 (int, Point2D) 组成的条目
如何在 Java 中做到这一点?
我尝试了以下失败。
HashMap hm = new HashMap();
hm.put(1, new Point2D.Double(50, 50));
【问题讨论】:
我想创建一个 map,其中包含由 (int, Point2D) 组成的条目
如何在 Java 中做到这一点?
我尝试了以下失败。
HashMap hm = new HashMap();
hm.put(1, new Point2D.Double(50, 50));
【问题讨论】:
Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));
【讨论】:
import java.util.Map; import java.util.HashMap;或import java.util.*;
还有一种更好的方法可以在初始化的同时创建地图:
Map<String, String> rightHereMap = new HashMap<String, String>()
{
{
put("key1", "value1");
put("key2", "value2");
}
};
【讨论】:
Java 9
public static void main(String[] args) {
Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
}
【讨论】:
对于较新的 Java 版本(即 Java 9 及更高版本),您可以使用:
Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)
一般来说:
Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)
但请记住,Map.of 仅适用于最多 10 条目,如果您有多个可以使用的 10 条目:
Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2, new Point2D.Double(100, 50)), ...);
【讨论】:
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
【讨论】:
Point2D.Double 看起来不像 Point2D =\
Map<int, Point2D> hm = new HashMap<int, Point2D>(),我收到此错误:令牌“int”上的语法错误,此令牌后应有尺寸。
感谢 Java 9,我使用了这种类型的 Map 人口。老实说,这种方法为代码提供了更多的可读性。
public static void main(String[] args) {
Map<Integer, Point2D.Double> map = Map.of(
1, new Point2D.Double(1, 1),
2, new Point2D.Double(2, 2),
3, new Point2D.Double(3, 3),
4, new Point2D.Double(4, 4));
map.entrySet().forEach(System.out::println);
}
【讨论】: