티스토리 뷰
Public Class Test {
private String[] locations;
public void setLocations(String... locations) {
this.locations = locations
}
}
java에서 가변인자 사용하는 내용은
http://omen666.tistory.com/229
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
java 1.5부터 추가되었고 메소드 호출시 전달된 인자의 갯수를 자신의 크기로 하는 배열을 만들어서 호출된 메소드에 전달한다.
즉 받는 입장에서는 가변인자가 배열로 들어온다고 생각하면 된다.
더 나아가서 가변인자대신에 배열을 직접 인자로 넘겨도 된다.
여기까지 중요 지식 한가지
그런데 가변인자 받는 코드를 살펴보면 가변인자를 받아서 enhanced for loop로 루핑하는 코드들을 많이 볼 수 있다.
위의 코드 예를 들면
public void setLocations(String... locations) {
for(String location: locations) {
..........
}
}
여기서 생각을 해보면 가변인자는 배열로 넘어왔는데 enhanced for loop로 돌려볼 수 있다라.
enhanced for loop를 간단히 for each문이라고 불러보면
for each문은 보통 Iterable을 구현하고 있는 collection에 담긴 내용들을 루핑할 수 있는건데
Array 객체가 Iterable을 구현했나? 라는 생각이 났고 검색해보니 스택오버플로우에 비슷한 질문이 있었다.
http://stackoverflow.com/questions/1160081/why-is-an-array-not-assignable-to-iterable
Unfortunately, arrays aren't '
class
-enough'. They don't implement theIterable
interface.Since an array isn't an object in the normal sense, it can't implement the interface.
The reason you can use them in for-each loops is because Sun added in some syntatic sugar for arrays (it's a special case).
Since arrays started out as 'almost objects' with Java 1, it would be far too drastic of a change to make them real objects in Java.
배열이 iterable을 구현한게 아니라 썬에서 Collection들 뿐만 아니라 배열도 루핑하기 위해서 부가적인 기능을 넣어주었다라고 해석할 수 있다.
이렇게 한 이유는 아무래도 오래전부터 배열을 많이 썼기때문에 호환성차원에서 지원인것 같다.
enhanced-for 문 얘기가 나왔으니 읽을만한 참고자료를 나열해보자
자기가 만든 객체에 enhanced for loop 사용할 수 있게끔 하기
https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with
enhanced for loop에 널 체크 적용하기
http://stackoverflow.com/questions/2250031/null-check-in-an-enhanced-for-loop
enhanced for loop에 널객체를 인자로 넘기면 익셉션이 발생한다. 미리 체크해서 예방하는 방법
Java Collections API에 대해 모르고 있던 5가지 사항, Part 1
http://www.ibm.com/developerworks/kr/library/j-5things2.html
Java Collections API에 대해 모르고 있던 5가지 사항, Part 2
http://www.ibm.com/developerworks/kr/library/j-5things3.html
탄생배경과 함께 한계점을 파악해보자
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
The for-each loop hides the iterator, so you cannot call
remove
. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
iterator를 숨기기때문에 remove를 부를 수 없고 따라서 필터링 용도로 사용하기 적당하지 않다. 비슷하게 안의 element들을 서로 바꿔치기 할때도 적당하지 못하다. 병렬적으로 여러개 컬렉션을 루핑하는데 사용하기도 좀 어렵다.