NoSuchElementException

Neue Frage »

Auf diesen Beitrag antworten »
Shizmo NoSuchElementException

Hallo, ich habe eine NoSuchElementException und ich komm nicht drauf:
Wenn ich Zeile 31 weglasse funktioniert es komischerweise...

code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
import java.util.*;
public class Test{
	
	public static class Testing{
		private int id;
		
		public Testing(int id){
			this.id = id;
		}
		
		public int getID(){
			return id;
		}
	}
	
	private static ArrayList<Testing> nodes = new ArrayList<>();

	public static void main(String[] args) {
		
		ArrayList<Integer> list = new ArrayList<>();
				
		Testing t1 = new Testing(1);
		Testing t2 = new Testing(2);
		
		nodes.add(t1);
		nodes.add(t2);
		
		Iterator<Testing> i = nodes.iterator();
		
		while(i.hasNext()){
			if (i.next().getID() == 2)
				System.out.println(i.next());
		}
	}
}


Lg
 
Auf diesen Beitrag antworten »
eulerscheZahl

Schau dir mal an, was next() macht.

Ablauf:
du prüfst, ob es noch Einträge gibt (der nächste ist id=1)
du holst id=1, was nicht 2 ist.
du prüfst, ob es noch Einträge gibt (der nächste ist id=2)
du holst id=2
du gibst aus, was als nächstes in der Liste steht - da kommt aber nichts mehr.

Speichere i.next() in einer temporären Variable ab.
Auf diesen Beitrag antworten »
Shizmo

Aha, also ich schicke den Iterator einmal zu weit weiter, alles klar, danke schön.
 
Neue Frage »
Antworten »


Verwandte Themen