0

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?

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

Sign up to request clarification or add additional context in comments.

4 Comments

You should start your for at 0. It's not an useful check but it's better than returning false if there is only one value in the List
If there is only one element in the list, the for block is not executed and true is returned.
The i < list.size() condition will not let it run (1 < 1 is false). Anyway, you can try it out in your IDE.
Glad I still remember some Java :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.