我创建了一个如下所示的ArrayList:
def list = new ArrayList()
Run Code Online (Sandbox Code Playgroud)
但是codenarc报告说它像下面一样警告.
ArrayList objects are better instantiated using the form "[] as ArrayList"
Run Code Online (Sandbox Code Playgroud)
有什么更好的实例化集合的方法?
tim*_*tes 17
你可以做:
def list = [] // Default is ArrayList
def list = [] as ArrayList
ArrayList list = []
Run Code Online (Sandbox Code Playgroud)
对于HashMap:
HashMap map = [:]
def map = [:] as HashMap
Run Code Online (Sandbox Code Playgroud)
在这种情况下,默认值为LinkedHashMap:
def map = [:]
Run Code Online (Sandbox Code Playgroud)
典型的是:
def list = []
Run Code Online (Sandbox Code Playgroud)
其他选择包括
def list = new ArrayList()
def list = new ArrayList<Foo>()
List list = new ArrayList()
def list = [] as ArrayList
List list = [] as ArrayList
Run Code Online (Sandbox Code Playgroud)
而且当然:
List<Foo> list = new ArrayList<Foo>();
Run Code Online (Sandbox Code Playgroud)
存在类似的选择HashMap使用[:].
但是codenarc报告说它像下面一样警告.
ArrayList objects are better instantiated using the form "[] as ArrayList"
Run Code Online (Sandbox Code Playgroud)
IMO,这是对Codenarc的不好建议,因为它假定实现类型[]是ArrayList.今天这是真的,但可能并非总是如此.
创建List实现的最简单/最佳/通常方式是:
def list = []
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我会写一些类似的东西
List<String> list = []
Run Code Online (Sandbox Code Playgroud)
只是为了使这个列表应该包含的内容更加明显,即为了代码可读性.如果我想创建一个特定类型的列表,我会实例化一个List"Java方式"
List<String> list = new SomeCustomListImplementation<String>()
Run Code Online (Sandbox Code Playgroud)
但实际上我不记得曾经这样做过.
| 归档时间: |
|
| 查看次数: |
19684 次 |
| 最近记录: |