java中list的remove()问题
写了一段应用remove的代码如下String[]food={"bread","cream","butter","peanut","milk"};LinkedList<S...
写了一段应用remove的代码如下
String[] food={"bread","cream","butter","peanut","milk"};
LinkedList<String> l1= new LinkedList<String>();
System.out.println("..............."+l1);//输出 [bread, cream, butter, peanut, milk]
String[] xfood={"bread"};
l1.remove(xfood);
System.out.println("..............."+l1);//输出依然为[bread, cream, butter, peanut, milk]
但是如果将l1.remove(xfood);改为l1.remove("xfood");就可以删除list中的bread。查了下资料,是因为
remove的源代码会在删除前进行比较(o==null ? get(i)==null : o.equals(get(i))),但是equals不是只比较内容么?而xfood的内容和list.get(0)的内容是一样的?不是很理解,烦请大神详细解释下~
相关资料:
http://blog.csdn.net/will_awoke/article/details/6528872
主要就是不明白equals的用法,看了定义也不太懂。。。希望有人能帮我详细解释下,谢谢。 展开
String[] food={"bread","cream","butter","peanut","milk"};
LinkedList<String> l1= new LinkedList<String>();
System.out.println("..............."+l1);//输出 [bread, cream, butter, peanut, milk]
String[] xfood={"bread"};
l1.remove(xfood);
System.out.println("..............."+l1);//输出依然为[bread, cream, butter, peanut, milk]
但是如果将l1.remove(xfood);改为l1.remove("xfood");就可以删除list中的bread。查了下资料,是因为
remove的源代码会在删除前进行比较(o==null ? get(i)==null : o.equals(get(i))),但是equals不是只比较内容么?而xfood的内容和list.get(0)的内容是一样的?不是很理解,烦请大神详细解释下~
相关资料:
http://blog.csdn.net/will_awoke/article/details/6528872
主要就是不明白equals的用法,看了定义也不太懂。。。希望有人能帮我详细解释下,谢谢。 展开
1个回答
展开全部
这是linkedlist的官方API:http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
E remove()
Retrieves and removes the head (first element) of this list.
E remove(int index)
Removes the element at the specified position in this list.
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
上面写了remove有3种用法,但是你的xfood 是String[], 如果你定义 LinkedList<String[]>的话这个就可以用,
把 String[] xfood={"bread"}; 改成 String xfood="bread";
bread 应该就会被删除
E remove()
Retrieves and removes the head (first element) of this list.
E remove(int index)
Removes the element at the specified position in this list.
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
上面写了remove有3种用法,但是你的xfood 是String[], 如果你定义 LinkedList<String[]>的话这个就可以用,
把 String[] xfood={"bread"}; 改成 String xfood="bread";
bread 应该就会被删除
追问
囧,我的例子没举好,我主要想问的是equals这个问题,能否帮我看下这个链接里面的例子http://blog.csdn.net/will_awoke/article/details/6528872,非常感谢
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询