Is there any unordered and repeatable collection class in Java?

See English answers > does Java has multiset data structure like the one in C + + STL? 6

It seems that pool is a suitable collection, but it does not exist in Java The interface shall be as follows:

public interface Pool<T> {
    void set(T item);
    T get();
}

Does it exist somewhere?

Supplement:

I realized that I had misexpressed my ideas In fact, I hope to have such an interface:

public interface Pool<T> {
    void put(T item);
    T randomRemove();
}

In other words, I hope to get a project every time How can I achieve it?

Solution

You can implement the function of your pool < T > wrapper list < T >

public class ListPool<T> implements Pool<T> {
    private List<T> list = ArrayList<>();

    public void put(T t) {
        list.append(t);
    }

    public T randomRemove() {
        return list.remove(rand.nextInt(list.size()));
    }
}

This is not particularly effective because the deletion is O (n) on the standard list implementation However, an alternative implementation using ArrayList is a bit complex, but provides a randomremove. 0 with O (1) Our idea is to treat the list as a dynamic array and manage the "size" by ourselves

Something like this:

public class FasterPool<T> implements Pool<T> {
    private List<T> list = new ArrayList<>();
    private int size = 0;
    Random rand = new Random();

    public void put(T t) {
        if (size == list.size()) {
            list.append(t);
        } else {
            list.set(size,t);
        size++;
    }

    public T randomRemove() {
        int pos = rand.nextInt(size);
        T result = list.get(pos);
        if (pos < size - 1) {
            list.set(pos,list.get(size - 1));
        }
        list.set(size - 1,null);  // avoid memory leak ...
        size--;
        return result;
    }
}

Note: when you try to delete an element, neither version will handle the case where the pool is empty None has been compiled or tested Please process the code accordingly

Finally, if you try to implement it with an unordered collection type, you are unlikely to effectively delete random elements Tip: the first returned by the iterator that deletes the collection is not really random for any actual collection data structure This also applies to the (hypothetical) bag implementation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>