-1

我正在尝试编写一种方法来检查所有天气中的所有天气都Objects具有ArrayList相同的值。例如,在下面的代码中list1应该返回true,并且list2应该返回false...

list1=[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
list2=[1,3,4,2,4,1,3,4,5,6,2,1,5,2,4,1]

编写此方法的最佳方法是什么?有什么快速的方法可以做到这一点,还是我需要手动循环这些值?

4

1 回答 1

2

So, you need to check if all the values in a list are the same?

boolean checkList(List<Integer> list) {
  if (list.isEmpty())
    return false;

  int value = list.get(0);
  for (int i = 1; i < list.size(); ++i) {
    if (list.get(i) != value)
      return false;
  }

  return true;
}

but I'd be careful about null values in the list, too...

于 2012-04-17T15:45:56.577 回答