나는리스트 반복을 연습하고있다. 내 질문은, 왜이 두 가지 방법이 다른 결과를 낳는가하는 것입니다.왜이 두리스트 반복자는 다르게 동작합니까?
첫 번째 코드는 무한 루프를 인쇄합니다. 두 번째는 인덱스의 다음 String을 출력한다.
저는 자바를 처음 사용합니다. 이것은 제 첫 번째 언어이기도합니다.
public static void main(String[] args) {
String[] hi = {"yo", "wat", "sup"};
List<String> l1 = new ArrayList(Arrays.asList(hi));
while (l1.iterator().hasNext()) {
System.out.println(l1.iterator().next());
;
}
}
VS
public static void main(String[] args) {
String[] hi = {"yo", "wat", "sup"};
List<String> l1 = new ArrayList(Arrays.asList(hi));
Iterator<String> rator = l1.iterator();
while (rator.hasNext()) {
System.out.println(rator.next());
}
}
기본적으로 .iterator는 while 메서드가 실행될 때마다 새로운 iterator입니까? –
@TinLe 예, 그렇습니다. – hexafraction