Reputation: 1527
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
Upvotes: 0
Views: 275
Reputation: 41
Try this:
for (int i = 0; i < theArray.length - 1; i++) {
if (!hold.contains(theArray[i]))
hold.add(theArray[i]);
}
System.out.println(hold);
Upvotes: 0
Reputation: 641
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);
Upvotes: 0
Reputation: 1106
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]
Upvotes: 1
Reputation:
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.
Upvotes: 0