Several easier mistakes (1)
I. Increment cycle and decrement cycle
First look at an example:
Import java.util. *;
Import java.io. *;
Public class testclass {
Public static void main (String [] args) {
Vector vitems = new vector ();
Vitems.Add ("aa1");
Vitems.Add ("aa2");
Vitems.Add ("BB3");
Vitems.Add ("BB4");
/ / Now I want to delete all elements containing BB characters.
For (int i = 0; i IF (Vitems.Elementat (i) .tostring (). Indexof ("bb")! = - 1) { Vitems.Remove (i); } } For (int i = 0; i System.out.println (Vitems.Elementat (i) .tostring ()); } } } Look at the results, there is a BB4, take a closer analysis, when deleting the BB3, i = 2, then vitems.remove (2); then carry out the next loop, i = i 1 = 3, pay attention to the VItems at this time .Size () = 3 (Since the size is deleted, the size is smaller), so the loop is terminated, causing the BB4 until it is deleted. How can you delete it completely? We change the deleted loop: For (INT i = vitems.size () - 1; i> = 0; i -) { IF (Vitems.Elementat (i) .tostring (). Indexof ("bb")! = - 1) { Vitems.Remove (i); } } Once again, this is found correctly. The reason is that when deleting the elements behind, the previous order has not changed, and the loop traverses all the elements. In the first example, remove the front elements, the position of the back elements A change has changed, so there is an omission. Squeeze a little summarize: In the cycle for (int i = 0; i If X is changed in the cyclic body, you can try for (INT i = X; I> = 0; I -). This problem is still more common in Java or more common: such as looping all components on a panel. The first time I was issued in 9CBS, I wrote it, please forgive me! I hope that you will not waste everyone.