java 如何检查数组的所有元素是否相同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15861878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if all of an array's elements are the same
提问by Jerome Jello Baek
How can you know that all of the elements in an array are the same? For example, a[] = {0, 0, 0, 0, 0, 0, 0}
你怎么知道数组中的所有元素都相同?例如,a[] = {0, 0, 0, 0, 0, 0, 0}
How can you know that all elements in a[] are the same? I'm a noob, please answer in easy terms. Thanks! :)
你怎么知道 a[] 中的所有元素都是一样的?我是菜鸟,请简单回答。谢谢!:)
回答by
Compare the value of each cell in the array with one of the cells, eg. the first cell. If all comparisons show that the values are the same then then all values in the entire array are the same.
将数组中每个单元格的值与其中一个单元格进行比较,例如。第一个单元格。如果所有比较都显示值相同,则整个数组中的所有值都相同。
Here is an example of what it could look like:
下面是它的外观示例:
public static boolean allElementsTheSame(int[] array) {
if (array.length == 0) {
return true;
} else {
int first = array[0];
for (int element : array) {
if (element != first) {
return false;
}
}
return true;
}
}
回答by Antonio Giordano
I'll do it in c ok? a[] is the array allEquals is a booleans ArrayLenght the dimension of the array
我会在 c 中完成吗?a[] 是数组 allEquals 是布尔值 ArrayLenght 数组的维度
BOOL allEquals = true;
for (int i=1; i<ArrayLenght; i++) {
if (a[i-1] != a[i])
allEquals = false;
}
now in allEquals you have true if all elements are equals, false otherwise.
现在在 allEquals 中,如果所有元素都相等,则为 true,否则为 false。