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 d开发者_Go百科efined 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?
You could use something like
list1.sublist(list1.indexOf(first), list1.indexOf(last))
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:
import java.util.*;
public class Test {
public static void main(String[] args) {
String first = "beta";
String last = "delta";
List<String> list1 = new LinkedList<String>();
list1.add("alpha");
list1.add(first);
list1.add("gamma");
list1.add(last);
list1.add("epsilon");
boolean firstFound = false;
for (String s : list1) {
if (firstFound || (firstFound = s == first))
System.out.println(s);
if (s == last)
break;
}
}
}
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 ==
returns true
iff they refer to the same object, which seems to be exactly what you want.
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
List<WrapperObject<Object>> aList = new LinkedList<WrapperObject<Object>>();
Now you can verify the equality of the entries by checking the wrappers instead of the wrapped objects.
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:
boolean start = false;
for(Object o : list){
if(o.equals(first){
start = true;
}else if(o.equals(last)){
break;
}
if(start){
// do something
}
}
Or rather use the answer of aioobe
精彩评论