简体   繁体   中英

How to extend the java HashSet class with a new function?

I'm making an android app. I would like to extend the HashSet class and add to it a new function that picks a random element from the set. Everything else should behave as the normal HashSet.

So I thought of having this class:

public class RandomHashSet<E> extends HashSet<E> {
    private Random mRand = new Random();

}

And I want to add to it a function that performs this code on the HashSet:

if (set.size() == 0) {
    return null; 
}
int index = mRand.nextInt(set.size());
Iterator<Object> iter = set.iterator();
for (int i = 0; i < index; i++) {
    iter.next();
}
return iter.next();

However, I'm not sure how to implement this function within the class, specifically how to call the instantiated set and how to iterate it.

In HashSet source code I see that they init a variable called 'map':

map = new HashMap<>();

For example, the HashSet add() function is implemented like this:

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
}

Can I also use 'map' in my function somehow (being private)?

import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;

public class RandomHashSet<E> extends HashSet<E> {
    private Random mRand = new Random();

    public E randomElement() {
        if (size() == 0) {
            return null;
        }
        int index = mRand.nextInt(size());
        Iterator<E> iter = iterator();
        for (int i = 0; i < index; i++) {
            iter.next();
        }
        return iter.next();
    }
}

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