如何将我的列表items
转换为CountedItem[]
?
import java.util.LinkedList;
import java.util.Collections;
import java.util.Comparator;
public class CountedSet<E>
{
LinkedList<CountedItem<E>> items = new LinkedList<CountedItem<E>>();
private final Comparator<CountedItem<E>> comparator = new Comparator<CountedItem<E>>()
{
@Override
public int compare(final CountedItem<E> o1, final CountedItem<E> o2)
{
return Integer.valueOf(o1.getCount()).compareTo(Integer.valueOf(o2.getCount()));
}
};
public CountedSet()
{
}
public CountedItem<E> add(E item)
{
CountedItem<E> currentItem = null;
for (CountedItem<E> listItem : items)
if (listItem.getItem().equals(item))
{
currentItem = listItem;
break;
}
if (currentItem != null)
currentItem.increment();
else
{
currentItem = new CountedItem<E>(item);
items.add(currentItem);
}
return currentItem;
}
public CountedItem<E>[] getSortedArray()
{
Collections.sort(items, this.comparator);
CountedItem<E>[] array = items.toArraySomeHow();
return array;
}
}
除了我想在public CountedItem<E>[] getSortedArray()
(最后一种方法)中这样做之外,我没有太多细节可以告诉你。此外,这样做会导致错误:
CountedItem<E>[] array = items.toArray(new CountedItem<E>[items.size()]);
// ERROR - Cannot create a generic array of CountedItem<E>. ^