简体   繁体   中英

Problem removing duplicates from an ArrayList using public static void removeDuplicate(ArrayList<Integer> list)

I know it is better ways to remove duplicates from a list but my teacher for some reason wants us to use this certain method.

My code works to an extent. For example if I enter "34 2 12 5 2 2 34 12 34 2" as my ten numbers the output will be, "The distinct integers are: 34 2 12 5 2". For some reason 2 comes up twice and I can't figure out why.

import java.util.ArrayList;
import java.util.Scanner;

public class RemoveDuplicate {
public static void main(String[] args){
    Scanner input = new Scanner(System.in);

    ArrayList<Integer> list = new ArrayList<Integer>();

    System.out.print("Enter ten numbers: ");
    for(int i=0;i<10;i++) {
        list.add(input.nextInt());
    }

    input.close();

    removeDuplicate(list);

    System.out.print("The distinct integers are: ");
    for(int i=0; i<list.size();i++){
        System.out.print(list.get(i)+" ");
    }
}

public static void removeDuplicate(ArrayList<Integer> list){
    for(int i=0; i<list.size()-1;i++){
        for(int j=i+1;j<list.size();j++){
            if(list.get(j) == list.get(i)) {
                list.remove(j);
            }
        }
    }
}

Thanks for the help!

Review j<list.size();j++ and list.remove(j) , which skip over the second 2 entry when remove shortens the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM