Search code examples
javaandroidvariablescode-reuse

Changing different variables according to value for efficient code reuse


I have variables of type long: hour_6days, hour_7days, hour_8days and hour_13days.

I have a string array:

String[] jj = rule.split(del);

where jj[0] contains the one of the numbers 6 or 7 or8 or 13.

How to change the above long variables according to the value in jj[0] ?

For example, how can I write the below, such that right hand side of the assignment is equivalent to the left hand side variable like:

hour_6days = "hour_"+jj[0]+"6days"; //this is invalid as hour_6days is of long type.

To be more clear,

If jj[0] contains 6, then I will use long variable's hour_6days value. If jj[0] contains 7, then I will use the long variable's hour_7days value.

The values I am using to set certain TextView like:

TextView tt2 = (TextView) v.findViewById(R.id.th3);

tt2.setText(hour_7days);

UPDATE:

I want to reuse the code in order to avoid multiple conditions. As said, in some conditions I am using tt2.setText(hour_7days); and in some other conditions I am using tt2.setText(hour_6days); and so on. I want to avoid the conditions and just simple use tt2.setText(hour_6_or_7_or_8days).


Solution

  • Try using a Map, HashMap is a possible choice.

    HashMap<Integer, Long> dayValues = new HashMap<Integer, Long>();
    
    dayValues.put(6,  <put long value for 6 days here>);
    dayValues.put(7,  <put long value for 7 days here>);
    dayValues.put(8,  <put long value for 8 days here>);
    dayValues.put(13, <put long value for 13 days here>);
    
    ...
    
    tt2.setText(dayValues.get(jj[0]).toString());
    

    This will use the integer value in jj[0] to get the corresponding string value from the map and set it into tt2.