通过LinkedList中的索引删除
这不是我在现实生活中会做的事情,而是说:
LinkedList = a,b,c,d,e
我就得到了它们相应的索引。
比如说,我想删除 b (index=1) 和 d (index=3)
(即 c (index=j=2)
周围的值)
现在,我这样做(效果很好):
When j=2
LS.remove(j + 1); ----> j=3 (d removed)
LS.remove(j - 1); ----> j=1 (b removed)
并且 b 和 d
被删除。
但是,如果我这样做(不起作用):
When j=2
LS.remove(j - 1); ----> j=1 (b removed)
LS.remove(j); ----> j=2 (d is not removed) (used j because due to above removal, LL has adjusted it self)
即当我首先移动“c”之前的值时,“d”不会被删除,并且 LL 保持原样。我想,我也在做同样的事情。
我在这里错过了什么吗?
更新:
因此,当我将签名 public void operation(String operator, Integer j) 更改为 public void operation(String operator, int j)
时,它起作用了。
This is not something which I would do in real life, but say:
LinkedList = a,b,c,d,e
and I get their corresponding index.
Say, I want to remove b (index=1) and d (index=3)
(i.e. values surrounding c (index=j=2)
)
Now,I do (which works fine):
When j=2
LS.remove(j + 1); ----> j=3 (d removed)
LS.remove(j - 1); ----> j=1 (b removed)
And b and d
are removed.
But if, I do (does not work):
When j=2
LS.remove(j - 1); ----> j=1 (b removed)
LS.remove(j); ----> j=2 (d is not removed) (used j because due to above removal, LL has adjusted it self)
i.e. when I move the value preceding 'c' first, 'd' is not removed and the LL stays as it is. I guess, I am doing the same thing.
Am I missing out on something here?
UPDATE:
So, when I change the signature public void operation(String operator, Integer j) to public void operation(String operator, int j)
, it worked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你错过了一些东西。这个完整的程序产生了预期的结果:
结果是:
You're missing something. This complete program produces the expected result:
The result is:
如果
j
的类型为 bigInteger
,则将调用LinkedList.remove(Object)
而不是LinkedList.remove(int)
。而这并不是你真正想要的。我认为没有任何理由在第二个示例中使用 big-Integer 作为
j
的类型,您应该使用原始int
。请检查为什么 Java Collections 删除方法不是通用的?了解原因
LinkedList
仍然具有remove(Object)
签名。If
j
is of type bigInteger
, thenLinkedList.remove(Object)
will be called instead ofLinkedList.remove(int)
. And that's not what you actually want.I don't see any reason to use big-Integer as the type of
j
in your second example, you should use primitiveint
.Please check Why aren't Java Collections remove methods generic? on why
LinkedList
still hasremove(Object)
signature.当您修改列表时,通过索引引用列表中的元素是一件很麻烦的事情——因此索引到元素的关系正在发生变化。这就是为什么在 Java 中
java.util .List
有一个方法List.listIterator()
,给出一个java.util.ListIterator
。有了这个,你可以编写一个像这样的方法:It's kind of a hairy thing to refer to elements of a list by index when you're modifying the list -- and so the relation from index to element is changing. This is why, in Java,
java.util.List
has a methodList.listIterator()
, giving ajava.util.ListIterator
. With this, you could write a method like so: