user1335361
user1335361

Reputation: 3323

check the values of the arraylist values in java

I'm trying to write a method that checks weather all the Objects in an ArrayList have the same value. For example, in the following code list1 should return true, and list2 should return 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]

What is the best way to write this method? Is there any quick methods to do this, or do I need to manually loop through the values?

Upvotes: 0

Views: 2485

Answers (1)

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

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...

Upvotes: 2

Related Questions