是他们的任何预定义函数,Java以便我可以检查a中的所有元素array是否不同?或者我是否必须从头开始编写函数才能找到它?
我有一个字符串array如下:
String[] hands = {"Zilch", "Pair", "Triple", "Straight", "Full House"};
Run Code Online (Sandbox Code Playgroud)
boolean noDupes(Object[] array) {
return Arrays.stream(array).allMatch(new HashSet<>()::add);
}
Run Code Online (Sandbox Code Playgroud)
一找到重复就停止,而不是遍历整个数组并最后比较大小.在概念上与Misha的答案相同,但使用Java 8功能(流和方法引用)在更高级别上工作.
使用HashSet并将 Hashset 的大小与原始数组的长度进行比较怎么样?
HashSet 去掉了重复项,因此如果大小与数组长度相同,则意味着所有数组元素都是不同的。
例子:
import java.util.Arrays;
import java.util.HashSet;
public class QuickTester {
public static void main(String[] args) {
String[] hands = new String[]{"Zilch", "Pair", "Triple",
"Straight", "Full House"};
HashSet<String> hs = new HashSet<>(Arrays.asList(hands));
if(hs.size() == hands.length) {
System.out.println("All elements in array are different!");
}
else {
System.out.println("Duplicates found in array!");
}
hands = new String[]{"Banana", "Apple", "Orange",
"Banana"};
hs = new HashSet<>(Arrays.asList(hands));
if(hs.size() == hands.length) {
System.out.println("All elements in array are different!");
}
else {
System.out.println("Duplicates found in array!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
All elements in array are different!
Duplicates found in array!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2149 次 |
| 最近记录: |