Informatiker Board (http://www.informatikerboard.de/board/index.php)
- Themengebiete (http://www.informatikerboard.de/board/board.php?boardid=1)
--- Praktische Informatik (http://www.informatikerboard.de/board/board.php?boardid=6)
---- Softwaretechnik (http://www.informatikerboard.de/board/board.php?boardid=18)
----- NoSuchElementException (http://www.informatikerboard.de/board/thread.php?threadid=3032)


Geschrieben von Shizmo am 15.05.2016 um 02:45:

  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



Geschrieben von eulerscheZahl am 15.05.2016 um 08:05:

 

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.



Geschrieben von Shizmo am 15.05.2016 um 10:45:

 

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


Forensoftware: Burning Board, entwickelt von WoltLab GmbH