简体   繁体   中英

When creating a list of Attribute values in Groovy (SoapUI), does the list get sorted automatically?

Basically, what I am trying is this: 1. From a SOAP API response, get a list of all the attribute values from a specific attribute. This attribute can exist multiple times in the response. 2. Copy this list into a 2nd list, and then sort the 2nd list 3. Compare both the lists to see if the 1st and 2nd lists are identical

However, I am facing an issue. When reading the attribute values from the SOAP API response, and then using the Collections.sort on the 2nd list, it seems to be sorting the 1st list as well.

Example:

<Home>
<ele attr="12"/>
<ele attr="11"/>
<ele attr="13"/>
</Home>

I tried the below 2 things:

Method 1:

distances.add(new BigDecimal(Home.ele[i].@'attr'[0]))
log.info distances
distanceSorted = distances
Collections.sort(distanceSorted)
log.info distances

This gives me the output as 11,12,13

Method 2:

distances.add(new BigDecimal(Home.ele[i].@'attr'[0]))
log.info distances
distanceSorted = distances
log.info distances

This gives me the output as 12,11,13

Any ideas why using the Collections.sort() on the distanceSorted list is affecting the distances list as well? Also, how can I fix this?

When you do this:

distanceSorted = distances

You just make both variables reference the same list. So when you do

Collections.sort(distanceSorted)

It sorts the list, so both variables now reference the sorted list

Replace both those lines with

distanceSorted = distances.sort(false)

The false tells the sort method to return a new list instead of sorting the original in place

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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