Collections.sort not sorting ArrayList as expected [beanshell, Java, JMeter]

徘徊边缘 提交于 2019-12-25 05:48:07

问题


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.


回答1:


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"


来源:https://stackoverflow.com/questions/32480031/collections-sort-not-sorting-arraylist-as-expected-beanshell-java-jmeter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!