简体   繁体   中英

arraylist.remove not working properly

I have a sorted array of integers and want to remove the duplicates, I wrote the following code

package practice;
import java.util.*;

public class pb1 {

public static void removeDup(int[] theArray){       

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


    for(int i=0;i<theArray.length-1;i++){


            hold.add(theArray[i]);

            //System.out.println(hold);

}
    for(int i=0;i<hold.size()-1;i++){
        if(hold.get(i)==hold.get(i+1)){
            hold.remove(i);
        }

    }
    System.out.println(hold);
}


public static void main(String[]args){
    int[] now={1,1,2,2,3,4,4,4,5,5,5,5};
    removeDup(now);



}

}

trying to delete the duplicates using the arraylist.remove method, but I can still see duplicates in my printed arraylist. I dont know why, pls can someone help me? thanks

An alternative solution. This takes advantage of the fact that a Set does not allow duplicate entries, and greatly simplifies your code.

public class pb1 
{

public static void removeDup(int[] theArray)
{       
    Set<Integer> hold=new TreeSet<Integer>();
    for(int i=0;i<theArray.length-1;i++)
    {
        hold.add(theArray[i]);
    }
    System.out.println(hold);
}


public static void main(String[]args)
    {
     int[] now={1,1,2,2,3,4,4,4,5,5,5,5};
     removeDup(now);
    }
}

Output:

[1, 2, 3, 4, 5]

Iterate backwards. Deleting items forward will delete the current element THEN increment the counter/index thus skipping possible duplicates. Replace your loop with:

for(int i = hold.size() - 1; i >= 1;i--){
    if(hold.get(i)==hold.get(i - 1)){
        hold.remove(i);
    }
}

EDIT: Your code fails at the three consecutive 4's When your index is at the first 4:

{1,1,2,2,3,>4,4,4,5,5,5,5}

it checks the next element. It deletes the current element because it sees a 4 ahead of it BUT, this is where the bug comes in.

{1,1,2,2,3,4,>4,5,5,5,5}

Upon deletion of the first 4, the succeeding array elements MOVE BACK and then you INCREMENT your counter thus skipping the other 4. Ergo, duplicates.

Why do you want to manually remove duplicates? You can copy list to set to remove duplicates and then copy from set to list again. Something like this

ArrayList aList = new ArrayList();
LinkedHashSet link = new LinkedHashSet();
link.addAll(aList);
aList.clear();
aList.addAll(link);

Try this:

for (int i = 0; i < theArray.length - 1; i++) {

           if (!hold.contains(theArray[i]))

                hold.add(theArray[i]);

}

System.out.println(hold);

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