dimanche 6 décembre 2015

Java generics convert String to Int or Float depending on parameter

I want to make generic function which fill up HashMap by either Integer or Double values depending on the type of parameter

basically I would like to put these two functions into one generic:

public static void MapFromString_Double( Map<String,Double> mp String s ){ 
    String [] words     = s.split("\\s+");
    for ( int i=0; i<words.length; i++ ){
        String [] tuple    = s.split("=");
        String name_string = tuple[0];
        String val_string  = tuple[1];
        Double num         = Double.parseDouble( val_string );
        mp.put( name_string, num ); 
    }
}

public static void MapFromString_Integer( Map<String,Integer> mp, String s ){ 
    String [] words     = s.split("\\s+");
    for ( int i=0; i<words.length; i++ ){
        String [] tuple    = s.split("=");
        String name_string = tuple[0];
        String val_string  = tuple[1];
        Integer num        = Integer.parseInt( val_string );
        mp.put( name_string, num ); 
    }
}

The input String s should be like IronOre=10.0 Coal=30.0 LimeStone=20.0

A non working code which ilustrates what I want si this:

public static <NUM extends Number> 
void MapFromString( Map<String,NUM> mp, String s ){ 
    String [] words     = s.split("\\s+");

    for ( int i=1; i<words.length; i++ ){
        String [] tuple = s.split("=");
        String name_string = tuple[0];
        String val_string  = tuple[1];


        // 1: is there any overriden string->Number conversion ?
        NUM num = Number.decode( val_string );

        // 2: alternative using some reflections ? Does not work either
        //NUM  num;
        //if( num instanceof Integer ){
        //  num = Integer.parseInt( val_string );
        //}else{
        //  num = Double.parseDouble( val_string );
        //}

        mp.put( name_string, num ); 
    }
}

I has probably a lot of connection to the problem that you cannot call constructor of parameter type in java, which is described here: Create instance of generic type in Java? But I'm hoping that in this simple case where parameter type is just a Number there will be some more clean way.





Aucun commentaire:

Enregistrer un commentaire