首页 > 解决方案 > 你需要 = new String[] 在数组中吗?

问题描述

String[] months = {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

System.out.println(Arrays.toString(months));

String[] months = new String[] {"January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

System.out.println(Arrays.toString(months));

这两个代码给出了相同的结果。所以我想知道哪种写作方式合适。

标签: javaarrays

解决方案


String[] arr = { "Alpha", "Beta" };

String[] arr = new String[] { "Alpha", "Beta" };

做同样的事情。第一个是在声明数组变量并在同一行初始化它时允许的快捷方式。

但是,在其他情况下,您必须使用new String[]来声明您正在创建的数组的类型。

String[] arr;
arr = { "Alpha", "Beta" }; // this will not compile
arr = new String[] { "Alpha", "Beta" }; // this will compile

推荐阅读