How can I check if all values in an array have a certain value?

前端 未结 2 1859
暖寄归人
暖寄归人 2021-01-16 17:08

In Java, given an array of values (say integers), is there a way to efficiently check to see if they all have a certain value?

For example, with an array of integers

2条回答
  •  一整个雨季
    2021-01-16 17:36

    public static boolean AreAllEqual(int[] numbers) {
        for(int i = 1; i < numbers.length; i++) {
            if(numbers[0] != numbers[i]) {
                return false;
            }
        }
        return true;
    }
    

    Using a function here will save you a lot of coding time and will also allow you to pass in arrays of arbitrary sizes (because you are iterating through the array according to its length).

提交回复
热议问题