gpt4 book ai didi

java - Java 集合方法 retainAll() 是否保证保留它修改的列表的顺序不变?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:20 27 4
gpt4 key购买 nike

它是否取决于哪个集合对象正在使用 retainAll?我正在使用字符串列表。

我进行了相当多的搜索,并在此处和网上的其他地方发现了一堆提示,它们应该保持列表的顺序不变,但没有明确的直接答案。如果已经回答,请指出正确的方向。

我什至找到了实现 retainAll 函数的代码示例,该函数指示未修改订单。但据我了解,这些示例可能并不完全是标准方法在下载的 java 包中的编码方式。从我自己使用该方法的测试来看,似乎也表明它保持秩序。但我想更加确定,因为我正在进行的测试特别依赖于保持有序的列表。

最准确地说,我希望这个函数真实可靠。

 /**
* This function takes the expected list and verifies it is contained within the actual list, in the expected order
* @param expectedList {@link List} List ordered as it should be to pass criteria
* @param actualList {@link List} List ordered as it exists in the product
* @return {@link Boolean} returns true when the expectedList is ordered within the actualList correctly
*/
static boolean verifyOrder(List<String> expectedList, List<String> actualList)
{
boolean ordered = false

if (expectedList == actualList)
ordered = true
else
{
actualList.retainAll(expectedList)
if (actualList == expectedList)
ordered = true
}
return ordered
}

最佳答案

作为引用,假设调用是:

list.retainAll(coll)

否则这个问题就没有意义了,因为 list 是被修改的集合,并且是指定顺序的集合。

Is the Java collection method retainAll() guaranteed to leave the order of the list it modifies unaltered?

规范明确指出它list 中移除 不在 coll 中的元素,因此顺序问题取决于 >remove方法指定保留顺序。

既然你说“保留列表的顺序”那么答案是:是

但您也将其表述为 “是 Java collection 方法 retainAll()”,所以如果 list 不是 List 但是一些其他的集合类型,那么答案是否定的,因为不是所有的集合类型都保证顺序。

Can it depend on which collection object is using the retainAll?

因为 list使用方法的那一个,那么:否
好吧,假设它 List,但已经有人回答了。

如果您打算将 coll 称为“正在使用该方法的那个”,那么:否
然而,性能会受到 coll 集合类型的影响,因为实现使用 coll.contains() 来检查匹配,所以如果 coll 是一个 Set

关于java - Java 集合方法 retainAll() 是否保证保留它修改的列表的顺序不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034726/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com