Initializing Collection

from Java 2008/02/14 22:08

출처는 http://satukubik.com/2007/12/19/java-tips-initializing-collection/ 입니다.

Especially in unit test, we have to initialize an array or a collection. Well, for array, it’s OK… A simple code that we know can solve the problem:

String[] s = new String [] {"1", "2"};

But how about Collection? Normal way to initialize collection is something like this (which pretty ugly):

List<String> s = new ArrayList<String>();
s.add("1");
s.add("2");

I hardly find an elegant solution until I see this post. There are at least three better solution for the case.

First solution:

List<String> s = new ArrayList<String>() {{ add("1"); add("2"); }};

Which unfortunately, doesn’t pass Java Code Convention (that is, if you format the code, it will become uglier than the original).

List<String> s = new ArrayList<String>() {
{
add("1");
add("2");
}
};

Second solution:

List<String> s = Arrays.asList(new String[]{"1", "2"});

This solution is the best if you use Java 1.4 or before. But if you use Java 5, the third is more elegant:

List<String> s = Arrays.asList("1", "2");

Great!

EDIT: Rob Juurlink commented that this solution will create a fixed read only collection, so you may want to wrap it with ArrayList (or other Collection class) to make it writable


위 내용에 좋은 답글이 달려서 그 내용도 복사를 하였습니다.
* Christian Ullenboom

I like this trick:

List list = Arrays.asList( “1,2,3,4,5,6,7″.split(”,”) );


* CK

check out this code

JButton button = new JButton();
button.setText(”hello”);
button.setRolloverEnabled(true);
button.setOpaque(true);

JButton anotherButton = new JButton() {{
setText(”hello”);
setRolloverEnabled(true);
setOpaque(true);
}};

I think this way of coding improve code readibility. Please comment.


'Java' 카테고리의 다른 글

String, StringBuffer, StringBuilder 선택 기준  (0) 2008/02/14
Generic Method 및 익셉션 처리 팁  (0) 2008/02/14
Initializing Collection  (0) 2008/02/14
Java char data type  (0) 2008/02/13
Java I/O 성능 향상을 위한 버전(JVM)별 내용  (0) 2008/02/12
Tag // , , ,