【发布时间】:2018-02-20 22:10:47
【问题描述】:
这将安全地返回 null 而不会引发任何异常
obj?.prop1?.prop2
我怎样才能为集合做到这一点,它不会抛出索引越界异常?
myarray[400] //how do I make it return null if myarray.size() < 400
Collections 有这样的操作符吗?
【问题讨论】:
标签: groovy
这将安全地返回 null 而不会引发任何异常
obj?.prop1?.prop2
我怎样才能为集合做到这一点,它不会抛出索引越界异常?
myarray[400] //how do I make it return null if myarray.size() < 400
Collections 有这样的操作符吗?
【问题讨论】:
标签: groovy
这是所有集合的默认行为,除了 groovy 中的数组。
assert [1,2,3,4][5] == null
def test = new ArrayList()
assert test[100] == null
assert [1:"one", 2:"two"][3] == null
如果您有一个数组,请将其转换为一个列表。
def realArray = new Object[4]
realArray[100] // throws exception
(realArray as List)[100] // null
您可以将列表和映射索引与? 运算符一起使用,方法与使用属性相同:
def myList = [[name: 'foo'], [name: 'bar']]
assert myList[0]?.name == 'foo'
assert myList[1]?.name == 'bar'
assert myList[2]?.name == null
【讨论】:
def a = [] ; println a[ -1 ] throws a java.lang.ArrayIndexOutOfBoundsException
mymap = null@987654328 @mymap?."$keyName"
test[100] 返回 null,BUT test.get(100) 抛出 IndexOutOfBoundsException。 test?.get(100) 也一样
您可以使用 get() 代替:
myarray?.get(400)
【讨论】:
IndexOutOfBoundsException,这实际上比返回 null 的 myarray[400] 的当前行为更糟糕。
? 只有在 myarray 为空时才有帮助。如果myarray 为空,则表达式的计算终止。否则它会继续并尝试访问第 400 个不存在的项目。我们会得到一个例外。