2

有什么方法可以避免get(0)在列表迭代中使用?

get(0)在迭代列表时使用它总是有风险的。

我确信在这个列表中我只有一个对象。

(PS 我记得我的上一位经理总是对我说要避免get(0)在列表迭代中使用。)

4

3 回答 3

9

不太清楚你所说的“有风险”是什么意思,但你可以考虑使用 Guava's Iterables.getOnlyElement

List<String> foo = getListFromSomewhere();
String bar = Iterables.getOnlyElement(foo);

这清楚地表明您希望只有一个元素。如果您认为可能没有元素,您可以使用允许您指定默认值的重载。

这样,当您要求元素时,您的期望就会被检查......但您还需要寻找什么并不明显。(你记得你的上一位经理警告过你这件事——但你记得他为什么警告你吗?)

于 2012-08-06T18:00:47.800 回答
2

Edit: I misuderstood the question, not realizing there was only a single item in the List. While my options still work, they aren't really necessary. However, I question the danger of using get(0) if your precondition is that there is a list with a single element.

You have a few options:

First is simply let the loop get the object for you with a for-each loop

 for(Object thing : things)

Second, is convert the list into another form and access it in the appropriate manner:

Object[] thingArray = things.toArray();
for(int i = 0; i < thingArray.length; i++)

Third is to use the ListIterator

ListIterator<Object> thingIterator = things.listIterator();
while(thingIterator.hasNext())
{
    Object thing = thingIterator.next();
于 2012-08-06T18:01:14.757 回答
0
Object objOne = list.iterator().next();
于 2012-08-06T18:27:54.953 回答