Jak o użyciu HashSet i porównując wielkość Hashset z długością oryginalnej tablicy?
HashSet pozbywa się duplikatów, więc jeśli rozmiar jest taki sam jak długość tablicy, będzie to oznaczać, że wszystkie elementy tablicy są różne.
Przykład:
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!");
}
}
}
wyjściowa:
All elements in array are different!
Duplicates found in array!
LinkedHashSet przechowuje tylko elementy unikalne. Tak, zrób to, Set arrToSet = new LinkedHashSet (Arrays.asList (ręce)); OR Collection arrToSet = new LinkedHashSet (Arrays.asList (arr)); –
http://stackoverflow.com/questions/203984/how-do--remove-repeated-elements-crom-arraylist –
Definiuj różne. Różne wartości? Różne obiekty? Jeśli pytasz konkretnie o ciągi w kodzie przykładowym, czy interesuje Cię porównywanie wielkości liter? –