Java-ArrayList去除重复项
在下面的示例中:
public static void main(String[] args){
List<String> list = new ArrayList<String>();
list.add("hi");
list.add("hi");
list.add("hi");
list.remove("hi");
System.out.println(list); //prints [hi, hi]
}
ArrayList 减一,但它删除的是哪一个?它会删除最后插入的还是最早插入的?
In the following example:
public static void main(String[] args){
List<String> list = new ArrayList<String>();
list.add("hi");
list.add("hi");
list.add("hi");
list.remove("hi");
System.out.println(list); //prints [hi, hi]
}
The ArrayList is reduced by one but which one does it remove? Does it remove the last inserted or the earliest inserted one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 文档 -
从此列表中删除第一次出现的指定元素(如果存在)。
From the docs -
Removes the first occurrence of the specified element from this list, if it is present.
自
List#add ()
被记录为添加到列表的 end,并且列表#据记录,remove(Object)
返回它遇到的第一个匹配项,上面的调用将删除字符串“hi”最早插入的实例。由于列表中三个对象的打印表示形式完全相同,因此很难看出行为上的差异。但是,如果您在调试器中查看实例地址,并注意哪一个首先进入列表,您将确认它也是第一个也是唯一一个要删除的地址。
在您的情况下,考虑到您使用的是字符串文字,它们会被编译器截留(根据JLS 的§3.10.5),因此您会在列表中看到三个相同的实例。为了生成不同的
String
实例,请尝试将三个插入调用更改为以下内容:将使用这些语句在调试器中看到的内容与原始程序进行比较。你看到有什么不同吗?
请注意,如果 上面的
String
实例h
被声明为 final,那么这三个串联实际上都将是实习,产生相同String
实例被添加到列表中三次。感谢@xehpuk 纠正了我最初关于最终限定符的错误。Since
List#add()
is documented to add to the end of the list, andList#remove(Object)
is documented to return the first matching item it encounters, your call above will remove the earliest inserted instance of the string "hi."Since the printed representation of the three objects in the list are all the same, it's hard to see the difference in behavior. However, if you look at the instance addresses in a debugger, noting which one entered the list first, you'll confirm that it's also the first—and only—one to be removed.
In your case, given that you're using string literals, they are interned by the compiler (per §3.10.5 of the JLS), so you'll see three of the same instance present in your list. In order to produce distinct
String
instances, try changing your three insertion calls to the following:Compare what you see in the debugger using those statements with your original program. Do you see a difference?
Note that if the
String
instanceh
above is declared as final, then the three concatenations will in fact all be interned, yielding the sameString
instance being added to the list three times. Thanks to @xehpuk for correcting my initial mistake regarding the final qualifier.它将删除它遇到的第一个事件,即您添加的第一个事件。
It will remove the first occurence it encounters, so the first one you added.