Well, this method is managing a conversion which accepts a list as a parameter, but definately doesn't look scalable.
List<Long> array_list_data= new ArrayList<>();
public void get_Data() {
long0 = array_list_data.get(0);
long1= array_list_data.get(1);
long2= array_list_data.get(2);
}
Afterwards, it will create a different class with the long
fields.
However, what if we have to expand this data to a 100 parameters on this list?
What I have done so far is:
List<Long> array_list_data= new ArrayList<>();
public void get_Data() {
int k = 0;
long0= array_list_data.get(k);
long1= array_list_data.get(k++);
long2= array_list_data.get(k++);
}
Why incrementing k
is not the right way to do it?
k++
performs a post-increment. In other words, the value of the expression is the original value of k
, and then k
is incremented. It's still incremented before the method is called, but the value passed as the argument is the value before the increment takes place. In other words, a call of:
x = list.get(k++);
is equivalent to:
int tmp = k;
k = k + 1;
x = list.get(tmp);
So if you actually had:
memory_version = array_list_data.get(k++); // Calls with 0, then k=1
mains_voltage_min = array_list_data.get(k++); // Calls with 1, then k=2
mains_voltage_max = array_list_data.get(k++); // Calls with 2, then k=3
then it would be fine, and equivalent to your first code. Your current problem is that you've actually got:
memory_version = array_list_data.get(k); // Calls with 0, then k=0
mains_voltage_min = array_list_data.get(k++); // Calls with 0, then k=1
mains_voltage_max = array_list_data.get(k++); // Calls with 1, then k=2
However, I'd suggest that if you're modelling the data in a class using a collection as a field, you may well be better off with a separate field for each value. (You may create an instance of the class by extracting the data from a list, of course, but that's a different matter.)
See more on this question at Stackoverflow