Вытащить HashSet из ключей HashMap?

Monkeypatch the library?

Например,

import other_library
other_library.function_or_class_to_replace = new_function

Poof, он возвращает все, что вы хотите, чтобы он возвращал.

Monkeypatch A. new для возврата экземпляра B?

После вызова obj = A () измените результат так, что obj. class = B ?

6
задан Haes 26 October 2009 в 16:36
поделиться

5 ответов

Why do you specifically need a HashSet?

Any Set have the same interface, so typically can be used interchangeably, as good-practices requires that you use the Set interface for all of them.


If you really need so, you could create one from the other. For generic code, it could be:

    Map<B, V> map = ...;
    HashSet<B> set = new HashSet<B>(map.keySet());
19
ответ дан 8 December 2019 в 02:40
поделиться

Assuming that the word 'efficient' is the key part of your question, and depending what you want to do with the set, it might be an idea to create your own subclass of HashSet which ignores the HashSet implementation and presents a view onto the existing map, instead.

As a partially implemented example, it might look something like:

public class MapBackedHashSet extends HashSet
{
    private HashMap theMap;

    public MapBackedHashSet(HashMap theMap)
    {
        this.theMap = theMap;
    }

    @Override
    public boolean contains(Object o) 
    {
        return theMap.containsKey(o);
    }

    /* etc... */
}

If you don't know how the class will be used, you'll need to take care to override all the relevant methods.

6
ответ дан 8 December 2019 в 02:40
поделиться
HashSet myHashSet = new HashSet(myHashMap.keySet());

Не пробовал.

4
ответ дан 8 December 2019 в 02:40
поделиться

Set set = new HashSet (map.keySet ());

2
ответ дан 8 December 2019 в 02:40
поделиться

Не можете ли вы создать HashSet из существующего Set ? Но (что более важно) почему вы беспокоитесь о реализации, возвращаемой вам методом keySet () ?

3
ответ дан 8 December 2019 в 02:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: