您好,请您帮我解决阵列中的重复项。
public class main {
public static void main(String[] args) {
String [] arr = {"Barcelona","Watford","Manchester United","Real Mandrid","Barcelona","Machester United","city"};
int[] arraya = { 1, 2, 3, 4, 2, 3, 1,11 }; // input array
int L = arr.length;
for (int i = 0; i < L; i++) {
System.out.print(" " + arr[i]);
}
System.out.println("\n" );
for (int i = 0; i < (L- 1) ; i++) {
for (int j = i + 1; j < L; j++) {
if(arr[i].equals(arr[j]));{
arr[j] = arr[L -1];
L--;
}
}
}
for (int i = 0; i < L; i++) {
System.out.print(" " + arr[i]);
}
}
}
我没有得到预期的答案,数组也删除了唯一值。
答案 0 :(得分:1)
您可以使用Set
,它将删除重复项。
要将数组转换为set
,只需使用以下命令:
Set<String> mySet = new HashSet<>(Arrays.asList(arr));
答案 1 :(得分:0)
在此;
之后,您还有if(arr[i].equals(arr[j]))
吗?
我认为,如果删除它,您的问题就可以解决。
答案 2 :(得分:0)
public class main {
public static void main(String[] args) {
String [] arr = {"Barcelona","Watford","Manchester United","Real Mandrid","Barcelona","Manchester United","city"};
int L = arr.length;
for (int i = 0; i < L; i++){
System.out.print(" " + arr[i]);
}
System.out.println();
for (int i = 0; i < L - 1 ; i++) {
for (int j = i + 1; j < L; j++) {
if(arr[i].equals(arr[j])){
arr[j] = arr[L -1];
L--;
j--;
}
}
}
for (int i = 0; i < L; i++){
System.out.print(" " + arr[i]);
}
System.out.println();
}
}
结果:
Barcelona Watford Manchester United Real Mandrid Barcelona Manchester United city
Barcelona Watford Manchester United Real Mandrid city