Pergunta

I have a function which has to 2 lists of different types a parameter inputs. To optimize, I want to create a HashSet / Hashtable (either of them ) of type of smallest list. Is there a way in a java to decide the type of Set at runtime ?

Current code:

   public static void innerJoinHash(List<SportsMan> sportsMans, List<Sport> sportList) {
        if (sportsMans.size() < sportList.size()) {
            Set<SportsMan> set = new HashSet<SportsMan>();
        } else {
            Set<Sport> set = new HashSet<Sport>();
        }
    }

What I want to do:

public static void innerJoinHash(List<SportsMan> sportsMans, List<Sport> sportList) {
    Set< // some magic //> set       
       if (sportsMans.size() < sportList.size()) {
         set = new HashSet<SportsMan>();
    } else {
        set = new HashSet<Sport>();
    }
}
Foi útil?

Solução

You can try with Java Generics. Set<E> customSet=new HashSet<E>();

That is a way you can use assign data type in run time.

  public static void innerJoinHash(List<SportsMan> sportsMans, List<Sport> sportList) {
  Set set = new HashSet();  
  if (sportsMans.size() < sportList.size()) {
        set.addAll(sportsMans)
    } else {
        set.addAll(sportList);
    }
  }

Outras dicas

The "// some magic //" you're looking for is the most specific common supertype of Sport and SportsMan. I.e., if both classes implement or extend a common interface, you can use that. Otherwise, it will be Object:

Set<Object> set = new HashSet<>(
    sportsMan.size() < sportsList.size()
    ? sportsMan : sportsList);

Create the type of Set as Object and on the run time while retrieval you can always cast the object into required data type.

OR

public static void innerJoinHash(List<SportsMan> sportsMans, List<Sport> sportList) {    
       if (sportsMans.size() < sportList.size()) {
      Set set = new HashSet<SportsMan>();
    } else {
       Set set = new HashSet<Sport>();
    }
}

Maybe I am not understand you question, but what is wrong this this approach?

    Set myset = new HashSet();
    myset.add("Hello");
    myset.add(new Long(1));

If you dumb it down by using Set or Set you are getting no benefits of generics.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top