java - 你需要 = 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
推荐阅读
- c# - 如何通过office open xml标准创建/编辑excel
- java - 如何在所有 HttpSecurity 配置器中添加过滤器?
- java - 小米设备在后台运行时启用应用程序弹出窗口的权限
- c++ - 如何使用 C++ 模板推断 const char 字符串的编译时间大小?
- angular - mat-select 值未在路线更改时保存,Angular 8
- rundeck - rundeck 作业可以按顺序执行吗?
- c++ - 如何强制数组初始值设定项具有与数组大小相同的项目数?
- html - How to match Input to height of container?
- scala - Scala - 将 json 作为字符串返回的测试函数
- java - Spring boot 的 Arango Edge Creation 错误