简体   繁体   English

Collections.sort未按预期对ArrayList进行排序[beanshell,Java,JMeter]

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

I have some Java code which I am using in Beanshell processor (JMeter). 我有一些在Beanshell处理器(JMeter)中使用的Java代码。 This java code is simple and valid. 此Java代码简单有效。 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. 观察28,29,4,5,6,7,8,9,10,11在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. 我原本期望4、5、6、7、8、9、10、11、12 等,但我无法理解这种奇怪行为的原因。 Could it be because of some issue with 'array input data'? 可能是因为“数组输入数据”存在问题吗? Collections.sort seems to work fine; Collections.sort似乎工作正常; when I create a sample arraylist myself. 当我自己创建一个示例arraylist时。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM