5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java] foreachのコロンの右側

5
Posted at

なにこれ

Javaのforeach文(拡張for文)の、コロンの右側
すなわち
for( String s : list )
listの部分
これが何回実行されるのか、疑問に思ったわけです。

for( String s : getList() )
な~んて、メソッドを書いちゃった時。
まさかループするたびにgetList()するなんてないよね?
そんなことしてたらおかしいよね?

実験してみました。

実験

Java
public static void main( String[] args ) {
	for( String s : getList() ) {
		System.out.println( s );
	}
}

public static List<String> getList() {
	System.out.println( "getList()" );
	List<String> l = new ArrayList<>();
	l.add( "a" );
	l.add( "b" );
	l.add( "c" );
	return l;
}
出力
getList()
a
b
c

結論

納得の結果だった。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?