Java2 test

и задачки для интервью.
User avatar
Bravomail
Уже с Приветом
Posts: 886
Joined: 22 Feb 2001 10:01
Location: Russia, Ufa->Detroit, MI, USA

Java2 test

Post by Bravomail »

Dano:

public void printVector (ArrayList vec) {
Object item;
while (vec.listIterator().hasNext()) {
item=vec.listIterator().next();
System.out.println(item.toString());
}
}

Итак - на глаз виден цикл выдающий все элементы на консоль.
Некоторая неоптимальность кодирования -
не обращайте на это внимания.
Вопрос - будет ли работать эта программа?
AK70
Уже с Приветом
Posts: 3127
Joined: 10 Apr 2001 09:01
Location: MD

Java2 test

Post by AK70 »

vec.listIterator()

will bring the new itereator at every call [img:7f133d1ea1]images/smiles/icon_smile.gif[/img:7f133d1ea1]
User avatar
Bravomail
Уже с Приветом
Posts: 886
Joined: 22 Feb 2001 10:01
Location: Russia, Ufa->Detroit, MI, USA

Java2 test

Post by Bravomail »

<BLOCKQUOTE><font size="1" face="Arial, Verdana, Helvetica, sans-serif">quote:</font><HR>Originally posted by AK70:
<STRONG>vec.listIterator()

will bring the new itereator at every call [img:ef53b21a43]images/smiles/icon_smile.gif[/img:ef53b21a43]</STRONG><HR></BLOCKQUOTE>

So loop will be indefinite long.
That's actually taken out of real code. It was really interesting for me to realize that "nonoptimized" code sometimes doesn't work, even if it looks so
.
AK70
Уже с Приветом
Posts: 3127
Joined: 10 Apr 2001 09:01
Location: MD

Java2 test

Post by AK70 »

<BLOCKQUOTE><font size="1" face="Arial, Verdana, Helvetica, sans-serif">quote:</font><HR>Originally posted by Bravomail:
<STRONG>

So loop will be indefinite long.
</STRONG><HR></BLOCKQUOTE>

not necessarily. you pass the reference to the function. which means that you can empty the ArrayList in another thread. then your hasNext() will return "false" and the loop will end.

definitely, it's the bug

[ 29-10-2001: Message edited by: AK70 ]

Return to “Головоломки”