Today, the maintenance of the previous code, see List.sublist This method, has not touched before, on this is a small white, learning today:
There is a sublist method in Java.util.List that returns a view of the part of a list.
It returns the view of this part of the original list from [FromIndex, Toindex], which is the view, because in fact, the returned list is supported by the original list.
So, your " non-Structural modification" (non-structural changes) of the original list and the returned list will affect each other.
The so-called " non-structural modification " refers to modifications that do not involve changes in the size of the list. Conversely, structural modifications refer to changes to the size of the list.
So what happens if structural changes are involved?
If a structural modification is a returned sub list, then the size of the original list will also change;
In the case of a structural modification of the original list (excluding changes caused by the returned sub list), the returned sub list semantics will be undefined. In Abstractlist (the parent class of ArrayList), the specific representation of undefined is to throw a concurrentmodificationexception.
Therefore, if you have modified the size of the original list after you have called the sublist and returned the sub list, the previously generated sub list will be invalidated and become unusable.
How do I delete a section of a list, such as the 第2-5个 element of a list?
The method is: You can use the sublist behind the scenes or the original list of this feature, such as
List.sublist (from, to). Clear ();
Example code:
public static void Main (string[] args) {
list<string> parentlist = new arraylist<string> ();
for (int i = 0; i < 5; i++) {
Parentlist.add (string.valueof (i));
}
list<string> sublist = parentlist.sublist (1, 3);
for (String s:sublist) {
System.out.println (s);//output:1, 2
}
Non-structural modification by sublist, reflect Parentlist
Sublist.set (0, "new 1");
for (String s:parentlist) {
System.out.println (s);//output:0, new 1, 2, 3, 4
}
Structural modification by sublist, reflect Parentlist
Sublist.add (string.valueof (2.5));
for (String s:parentlist) {
System.out.println (s);//output:0, new 1, 2, 2.5, 3, 4
}
Non-structural modification by parentlist, reflect sublist
Parentlist.set (2, "New 2");
for (String s:sublist) {
System.out.println (s);//output:new 1, new 2
}
Structural modification by parentlist, sublist becomes undefined (throw exception)
Parentlist.add ("undefine");
for (String s:sublist) {
System.out.println (s);
// }
Sublist.get (0);
}
Summary of List.sublist in Java