I have the code below and I need to see whether or not there ar开发者_开发知识库e duplicates and if there are, then remove only one instance of it. If there is only one instance, it is still removed. I know I have to use a counter somehow and resize the array but I'm not really sure how.
Listable[]newitems = new Listable[items.length-1];
for(int i = 0;i<items.length;i++){
if(items[i]!=itemToRemove){
break;
}
else{
for(int j = i;j<items.length-1;++j){
newitems[j] = items[j+1];
}
}
items = newitems;
}
You need to loop through the array until you find an instance of the element to remove, then allocate a new array (since it needs to be shorter) and copy everything except the item to be removed from the original to the new array. Your code is stopping after the first item that is not the one you want to remove. Try this instead:
Listable[] newitems = items; // default in case itemToRemove isn't found
for (int i = 0; i<items.length; i++) {
if (items[i] == itemToRemove) {
newitems = new Listable[items.length - 1];
System.arraycopy(items, 0, newitems, 0, i);
System.arraycopy(items, i+1, newitems, i, items.length - i - 1);
break;
}
}
items = newitems;
It might be better to use items[i].equals(itemToRemove)
instead of ==
, depending on the requirements.
Use a LinkedHashSet. A Set is a collection that does not contain duplicate elements. A LinkedHashSet allows you to maintain the array order. If ordering is not important just use a HashSet.
Set<Listable> set = new LinkedHashSet<Listable>();
for(Listable l : items) {
set.add(l);
}
Listable[] newitems = set.toArray(new Listable[set.size()]);
This saves copying arrays multiple times but relies on the equals and hashCode methods of Listable working correctly to be able to distinguish unique elements.
I think the break
is throwing things off since it'll immediately terminate the loop. Is continue
what you're wanting instead? At first glance, most of the rest of the code looks like it would work. But what happens when you set items = newItems
in the for loop?.
If I read your description right, you just want to keep items when they are in the list 2 or more times.
// count the instances
LinkedHashMap<Listable,Integer> map = new LinkedHashMap<Listable, Integer>();
for(int i = 0; i < items.length; i++) {
int count = 1;
if (null != map.get(items[i])) {
count += map.get(items[i]);
}
map.put(items[i], count);
}
// add it to the new list if the count is more than 1
ArrayList newList = new ArrayList<Listable>();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if (((Integer)pairs.getValue()) > 1) {
newList.add(pairs.getKey());
}
}
return newList.toArray();
精彩评论