猿问

不使用方法删除数组重复项

您好,请您帮我解决阵列中的重复项。


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]);

        }

    }

}

我没有得到预期的答案,数组也删除了唯一值。


万千封印
浏览 143回答 3
3回答

qq_笑_17

public class main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String [] arr = {"Barcelona","Watford","Manchester United","Real Mandrid","Barcelona","Manchester United","city"};&nbsp; &nbsp; &nbsp; &nbsp; int L = arr.length;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < L; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" " + arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < L - 1 ; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int j = i + 1; j < L; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arr[i].equals(arr[j])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr[j] = arr[L -1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; L--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; j--;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < L; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" " + arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp;&nbsp; &nbsp; }}&nbsp; &nbsp;结果:Barcelona Watford Manchester United Real Mandrid Barcelona Manchester United cityBarcelona Watford Manchester United Real Mandrid city

largeQ

您可以使用Set它来删除重复项。要将数组转换为set仅使用此命令:Set<String>&nbsp;mySet&nbsp;=&nbsp;new&nbsp;HashSet<>(Arrays.asList(arr));

撒科打诨

你有;这个之后if(arr[i].equals(arr[j]))&nbsp;,我认为,如果你删除它,你的问题就解决了。
随时随地看视频慕课网APP

相关分类

Java
我要回答