I have some Java code which I am using in Beanshell processor (JMeter). This java code is simple and valid. It should simply sort the numeric arraylist but it is giving strange behavior:
// Input data is like below:
student_id_RegEx_1=13
student_id_RegEx_11=4
student_id_RegEx_12=23
student_id_RegEx_13=24
// CREATE ARRAY LIST AND STORE ELEMENTS IN IT
ArrayList strList = new ArrayList();
for (int i=0;i<25; i++){
strList.add(vars.get("student_id_RegEx_" + String.valueOf(i+1)));
}
// Print the ArrayList created by above method [output is]
vars.putObject("ArrayListBeforeSorting",strList);
ArrayListBeforeSorting=[13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 4, 23, 24, 25, 26, 27, 28, 29, 5, 6, 7, 8, 9, 10, 11]
// Sort the ArrayList
Collections.sort(strList);
//Print the sorted ArrayList [below is output]
vars.putObject("ArrayListAfterSorting",strList);
ArrayListAfterSorting=[10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 4, 5, 6, 7, 8, 9]
Observe the 28, 29, 4, 5, 6, 7, 8, 9, 10, 11 at end of sortedArrayList. I was expecting 4, 5, 6, 7, 8, 9, 10, 11, 12 and so on I cannot understand the reason behind this strange behavior. Could it be because of some issue with 'array input data'? Collections.sort seems to work fine; when I create a sample arraylist myself. Any comments on this behavior and solution would be appreciated. Thanks.
Instead of saving values of type String, save them as numbers:
String strValue = vars.get("student_id_RegEx_" + String.valueOf(i+1));
strList.add(Integer.parseInt(strValue));
Sorting as Strings works by comparing each character, one by one, for example:
2 4 5
| | | |
2 2 3 3
2 = 2
4 > 2 - therefore, "245" is "bigger" than "2233"