我想创建一个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));
Answers:
还有一种更好的方法来创建带有初始化的Map:
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"));
}
Map.of(1, "A", 2, "B", 3, "C")
更好
java: cannot find symbol symbol: method of(java.lang.String,double) location: interface java.util.Map
java -version
openjdk 11.0.8 2020-07-14 OpenJDK Runtime Environment (build 11.0.8+10-post-Ubuntu-0ubuntu120.04) OpenJDK 64-Bit Server VM (build 11.0.8+10-post-Ubuntu-0ubuntu120.04, mixed mode, sharing)
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);
}
Map<Integer, Double>