java:数组如果都一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4448698/
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
java: array if all the same
提问by Karem
I have a array:
我有一个数组:
int tarningar[] = new int[5];
That holds numbers. When all the numbers are the same, system.out.println('ok');
那持有数字。当所有数字都相同时,system.out.println('ok');
How can I do this?
我怎样才能做到这一点?
采纳答案by Boris Pavlovi?
boolean flag = true;
int first = tarningar[0];
for(int i = 1; i < 5 && flag; i++)
{
if (tarningar[i] != first) flag = false;
}
if (flag) System.out.println("ok");
回答by Andreas Dolk
All values are the sameis equivalent to All values are equal to any selected value.
所有值都相同相当于所有值都等于任何选定的值。
So just choose one as a referenceand compare this chosen value to all other values.
因此,只需选择一个作为参考,并将此选定值与所有其他值进行比较。
回答by Andreas Dolk
public class EqualArrayTest {
public static boolean isAllEqual(int[] a){
for(int i=1; i<a.length; i++){
if(a[0] != a[i]){
return false;
}
}
return true;
}
public static void main(String[] args){
System.out.println(isAllEqual(new int[]{2,2,2}));
System.out.println(isAllEqual(new int[]{2,2,1}));
}
}
回答by Jesper
Simple solution without a loop (and a fixed array length of 5):
没有循环的简单解决方案(并且固定数组长度为 5):
int v = tarningar[0];
if (tarningar[1] == v && tarningar[2] == v && tarningar[3] == v && tarningar[4] == v) {
System.out.println("All the same!");
}
回答by Mudassir
boolean isSame = true;
for(int i = 1; i < tarningar.length; i++) {
if (tarningar[i] != tarningar[0]) {
isSame = false;
}
}
if (isSame) {
System.out.println("OK");
}
回答by Ralph
import java.util.Arrays;
/**
* Don't take it serious.
* But it works.
*/
public class Demo {
public static boolean isAllSame(int... numbers) {
int[] firstItemArray = new int[numbers.length];
Arrays.fill(firstItemArray, numbers[0]);
return Arrays.equals(numbers, firstItemArray);
}
public static void main(String[] args) {
System.out.println(isAllSame(1,1,1,1));
System.out.println(isAllSame(1,1,1,2));
}
}
回答by kanbagoly
with Google's Guava:
使用谷歌的番石榴:
boolean allEqual = Sets.newHashSet(Ints.asList(tarningar)).size() == 1;
回答by sevenforce
In Java 8 with the stream API:
在带有流 API 的 Java 8 中:
Set<Integer> uniqueValues = Arrays.stream(tarningar)
.boxed()
.collect(Collectors.toSet());
boolean allEqual = uniqueValues.size() == 1;
If you used Integer[]
instead of int[]
the following is supported in Java 7 and before:
如果您使用Integer[]
的不是int[]
下面是支持的Java 7和之前:
// Integer[] tarninagr = ...
Set<Integer> uniqueValues = new HashSet<>(Arrays.asList(tarningar));
boolean allEqual = uniqueValues.size() == 1;
回答by Matthew
Here's a more succinct Java 8 streams example:
这是一个更简洁的 Java 8 流示例:
Arrays.stream(tarningar).distinct().count() == 1