数组中是否需要=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));

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

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

最新更新