Java 中的链表迭代
比如说,我有两个对 LinkedList List1 中的对象的引用:
LinkedList<Object> List1 = new LinkedList<Object>();
Object first;
Object last;
我不想使用这些对象的列表索引来引用它们,因为我的列表的长度发生了变化。我认为这是行不通的。 现在我想迭代由first 和last 定义的子列表,其中first 定义List1 中子列表的开头,last 定义List1 中子列表的结尾。
我现在的问题是,据我所知,我不能做这样的事情,
while (current != last){
// do something
current = someiterator.next();
}
因为我正在比较两个通常会指向不同位置的对象。此外,我也无法按引用的值进行比较,因为列表中的一个值可能会出现多次。 那么如何迭代 List1 的这个子列表呢?
Say, I have two references to an Object in a LinkedList List1:
LinkedList<Object> List1 = new LinkedList<Object>();
Object first;
Object last;
I don't want to use the list index of these objects to refer to them, because the length of my list changes. I think this would not work.
Now I want to iterate through the sublist defined by first and last, where first defines the beginning of the sublist in List1 and last defines the end of the sublist in List1.
My problem now is that AFAIK I can't do something like
while (current != last){
// do something
current = someiterator.next();
}
because I'm comparing two objects that in general will point to different locations. Furthermore, I also can't compare the references by their value, because the list may have one value appearing several times.
So how can I iterate through this sublist of List1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以使用类似
好的,我想我现在更好地理解你的问题了。上述方法将使用
.equals
方法,因此不比较引用。这可能是一个更适合您的解决方案:You could use something like
Ok, I think I understand your question better now. The above method will use the
.equals
method and thus not compare references. Here is probably a better solution for you:不,您的比较
while (current != last)
可以正常工作。在 Java 中,对象存在于堆中,您只能使用引用。使用==
比较两个引用会返回true
,前提是它们引用同一个对象,这似乎正是您想要的。No, your comparison
while (current != last)
will work fine. In Java, objects live on the heap and you only work with references. Comparing two references using==
returnstrue
iff they refer to the same object, which seems to be exactly what you want.如果你既不能依赖 == 也不能依赖 .equals(),我不明白你如何定义一个子列表......
If you cannot rely neither on == nor .equals(), I don't see how you could possibly define a sublist...
一种方法是不直接添加对象,而是创建一个包装器,这样您
现在就可以通过检查包装器而不是包装的对象来验证条目的相等性。
One way is not to add the objects directly, but to create a wrapper, so you will have
Now you can verify the equality of the entries by checking the wrappers instead of the wrapped objects.
您应该使用 Object.equals() 来比较您的对象。如果您的对象是真正的对象而不是原始对象或字符串(如果它们的值相等,它们就相等),您应该能够这样做:
或者更确切地说使用 aioobe 的答案
You should use Object.equals() to compare your objects. If your Objects are real Objects and not primitive or Strings (they equal if their value equals) you should be able to do so:
Or rather use the answer of aioobe