한 줄로 배열 목록의 초기화
-
05-07-2019 - |
문제
테스트 목적으로 옵션 목록을 만들고 싶습니다. 처음에 나는 이것을했다 :
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
그런 다음 코드를 다음과 같이 리팩토링했습니다.
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
더 좋은 방법이 있습니까?
해결책
실제로, 아마도 초기화하는 "가장 좋은"방법 일 것입니다. ArrayList
새로운 것을 만들 필요가 없기 때문에 작성한 방법입니다. List
어떠한 방식으로:
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
캐치는 그것을 언급하는 데 약간의 타이핑이 필요하다는 것입니다. list
사례.
인스턴스 이니셜 라이저 ( "더블 브레이스 초기화"라고도 함)가있는 익명의 내부 클래스를 만드는 것과 같은 대안이 있습니다.
ArrayList<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
그러나 나는 당신이 끝나는 것이 서브 클래스이기 때문에 그 방법을 너무 좋아하지 않습니다. ArrayList
인스턴스 이니셜 라이저가 있고 해당 클래스는 하나의 객체를 만들기 위해 만들어졌습니다. 이는 나에게 약간의 과도한 것처럼 보입니다.
좋은 점은 수집 리터럴 제안 ~을 위한 프로젝트 코인 받아 들여졌습니다 (Java 7에서 소개 될 예정이지만 Java 8의 일부일 가능성은 없습니다.) :) :
List<String> list = ["A", "B", "C"];
불행히도 그것은 불변의 초기화이기 때문에 여기서 당신을 도울 수 없습니다. List
대신 ArrayList
, 또한, 아직 구할 수 없습니다.
다른 팁
당신이 단지 그것을 List
- 배열 목록이어야합니까?
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
또는 요소가 하나만있는 경우 :
List<String> places = Collections.singletonList("Buenos Aires");
이것은 그것을 의미합니다 places
~이다 불변 (변경하려고 시도하면 UnsupportedOperationException
던질 예외).
콘크리트 인 돌연변이 목록을 만들기 위해 ArrayList
당신은 당신을 만들 수 있습니다 ArrayList
불변의 목록에서 :
ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
간단한 대답
Java 10, 11, 12 이상에서 :
var strings = List.of("foo", "bar", "baz");
Java 9 이상 :
List<String> strings = List.of("foo", "bar", "baz");
이것은 당신에게 불변을 줄 것입니다 List
, 따라서 변경할 수 없습니다.
대부분의 경우 당신이 그것을 미리 채우고있는 대부분의 경우 원하는 것입니다.
Java 8 이상 :
List<String> strings = Arrays.asList("foo", "bar", "baz");
이것은 당신에게 줄 것입니다 List
배열로 뒷받침되므로 길이를 변경할 수 없습니다.
그러나 당신은 전화 할 수 있습니다 List.set
, 여전히 변이 가능합니다.
당신은 할 수 있습니다 Arrays.asList
정적 수입으로 더 짧아집니다.
List<String> strings = asList("foo", "bar", "baz");
정적 가져 오기 :
import static java.util.Arrays.asList;
현대의 IDE가 당신을 위해 제안하고 자동으로 할 것입니다.
예를 들어 Intellij Idea에서 당신은 당신이 누르십시오 Alt+Enter
그리고 선택하십시오 Static import method...
.
그러나 Java 9를 단축하는 것은 권장하지 않습니다 List.of
방법, 그냥 가지고 있기 때문입니다 of
혼란스러워집니다.
List.of
이미 충분히 짧고 잘 읽습니다.
사용 Stream
에스
왜 List
?
Java 8 이상을 사용하면 a를 사용할 수 있습니다 Stream
더 유연한 :
Stream<String> strings = Stream.of("foo", "bar", "baz");
당신은 연결할 수 있습니다 Stream
에스:
Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
Stream.of("baz", "qux"));
또는 당신은 a에서 갈 수 있습니다 Stream
a List
:
import static java.util.stream.Collectors.toList;
List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());
그러나 바람직하게는 그냥 사용하십시오 Stream
a에 수집하지 않고 List
.
만약 너라면 진짜 구체적으로 필요합니다 java.util.ArrayList
(아마도 당신은 그렇지 않을 것입니다.)
인용합니다 JEP 269 (강조 광산) :
이있다 작은 세트 사전 정의 된 값 세트로 변이 가능한 수집 인스턴스를 초기화하기위한 사용 사례. 일반적으로 사전 정의 된 값을 불변의 컬렉션에 넣은 다음 사본 생성자를 통해 변이 가능한 컬렉션을 초기화하는 것이 바람직합니다.
당신이 원한다면 둘 다 미리 채워서 ArrayList
그리고 나중에 추가 (왜?)
ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
strings.add("baz");
또는 Java 8 이상 :
ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
strings.add("baz");
또는 사용 Stream
:
import static java.util.stream.Collectors.toCollection;
ArrayList<String> strings = Stream.of("foo", "bar")
.collect(toCollection(ArrayList::new));
strings.add("baz");
그러나 다시, 그냥 사용하는 것이 낫습니다. Stream
직접 수집하는 대신 a List
.
구현이 아닌 인터페이스로 프로그램
당신은 목록을 다음에 선언했다고 말했습니다 ArrayList
코드에서는 있지만 일부 구성원을 사용하는 경우에만 수행해야합니다. ArrayList
그건 아니에요 List
.
당신이 할 가능성이 가장 높습니다.
일반적으로 사용하려는 가장 일반적인 인터페이스별로 변수를 선언해야합니다 (예 : Iterable
, Collection
, 또는 List
)), 특정 구현으로 초기화하십시오 (예 : ArrayList
, LinkedList
또는 Arrays.asList()
).
그렇지 않으면 코드를 해당 특정 유형으로 제한하고 싶을 때 변경하기가 더 어려워집니다.
예를 들어, 당신이 통과하는 경우 ArrayList
a void method(...)
:
// Iterable if you just need iteration, for (String s : strings):
void method(Iterable<String> strings) {
for (String s : strings) { ... }
}
// Collection if you also need .size(), .isEmpty(), or .stream():
void method(Collection<String> strings) {
if (!strings.isEmpty()) { strings.stream()... }
}
// List if you also need .get(index):
void method(List<String> strings) {
strings.get(...)
}
// Don't declare a specific list implementation
// unless you're sure you need it:
void method(ArrayList<String> strings) {
??? // You don't want to limit yourself to just ArrayList
}
또 다른 예는 항상 변수를 선언하는 것입니다 InputStream
비록 그것은 보통 a FileInputStream
또는 a BufferedInputStream
, 언젠가는 곧 당신이나 다른 사람이 다른 종류의 다른 종류의 사용을 원할 것입니다. InputStream
.
간단한 크기 목록이 필요한 경우 1 :
List<String> strings = new ArrayList<String>(Collections.singletonList("A"));
여러 개체 목록이 필요한 경우 :
List<String> strings = new ArrayList<String>();
Collections.addAll(strings,"A","B","C","D");
수집 리터럴은 Java 8으로 만들지 않았지만 스트림 API를 사용하여 하나의 긴 줄에서 목록을 초기화 할 수 있습니다.
List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());
당신이 당신을 확인 해야하는 경우 List
이다 ArrayList
:
ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));
import com.google.common.collect.ImmutableList;
....
List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
와 함께 Java 9
, 제안 된 바와 같이 JDK 강화 제안 -269, 이것은 사용하여 달성 될 수 있습니다 컬렉션 리터럴 이제 -
List<String> list = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B", "C");
또한 비슷한 접근 방식이 적용됩니다 Map
또한 -
Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")
비슷합니다 수집 리터럴 제안 @coobird도 언급했듯이. JEP Doc에서도 더 명확 해졌습니다.
대안
언어 변경은 여러 번 고려되었으며 거부되었습니다.
JEP 186 Lambda-Dev, 2014 년 1 월 -3 월 토론
언어 제안은 이것에 요약 된 라이브러리 기반 제안보다 선호되었습니다. 메시지.
공장 방법을 만들 수 있습니다.
public static ArrayList<String> createArrayList(String ... elements) {
ArrayList<String> list = new ArrayList<String>();
for (String element : elements) {
list.add(element);
}
return list;
}
....
ArrayList<String> places = createArrayList(
"São Paulo", "Rio de Janeiro", "Brasília");
그러나 첫 번째 리팩토링보다 훨씬 낫지 않습니다.
유연성을 높이기 위해 일반적 일 수 있습니다.
public static <T> ArrayList<T> createArrayList(T ... elements) {
ArrayList<T> list = new ArrayList<T>();
for (T element : elements) {
list.add(element);
}
return list;
}
Java 9에서는 쉽게 초기화 할 수 있습니다 ArrayList
한 줄로 :
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
또는
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
Java 9 의이 새로운 접근 방식은 이전의 것보다 많은 장점이 있습니다.
자세한 내용은이 게시물을 참조하십시오 -> List.of와 Arrays.aslist의 차이점은 무엇입니까?
와 함께 일식 컬렉션 다음을 작성할 수 있습니다.
List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
또한 유형과 변이 가능하거나 불변의 유형에 대해 더 구체적 일 수 있습니다.
MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");
세트와 가방으로도 똑같이 할 수 있습니다.
Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");
Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");
메모: 나는 이클립스 컬렉션을위한 커피터입니다.
이 작업을 수행하는 가장 작곡 방법은 다음과 같습니다.
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);
다른 방법은 다음과 같습니다.
List<String> values = Stream.of("One", "Two").collect(Collectors.toList());
아래 코드를 다음과 같이 사용하십시오.
List<String> list = new ArrayList<String>() {{
add("A");
add("B");
add("C");
}};
아래 설명을 사용할 수 있습니다.
코드 스 니펫 :
String [] arr = {"Sharlock", "Homes", "Watson"};
List<String> names = Arrays.asList(arr);
(댓글이어야하지만 너무 길어서 새로운 답장이어야합니다). 다른 사람들이 언급했듯이 Arrays.asList
방법은 고정 된 크기이지만 이것이 유일한 문제는 아닙니다. 또한 상속을 잘 처리하지 않습니다. 예를 들어 다음이 있다고 가정합니다.
class A{}
class B extends A{}
public List<A> getAList(){
return Arrays.asList(new B());
}
위의 결과로 컴파일러 오류가 발생합니다 List<B>
(Arrays.aslist)에 의해 반환되는 것입니다. 서브 클래스가 아닙니다. List<A>
, B 형의 객체를 A에 추가 할 수 있지만 List<A>
물체. 이 문제를 해결하려면 다음과 같은 작업을 수행해야합니다.
new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))
이것은 아마도이 작업을 수행하는 가장 좋은 방법 일 것입니다. 무한한 목록이 필요하거나 상속을 사용해야하는 경우.
처럼 톰이 말했다:
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
그러나 ArrayList를 원한다고 불평 했으므로 먼저 ArrayList가 목록의 서브 클래스이고 간단히이 줄을 추가 할 수 있음을 알아야합니다.
ArrayList<String> myPlaces = new ArrayList(places);
그러나 그것은 당신이 '성능'에 대해 불평하게 만들 수 있습니다.
이 경우 나에게 의미가 없습니다. 목록이 사전 정의되어 있기 때문에 배열로 정의되지 않았기 때문에 (초기화시 크기가 알려져 있기 때문에) 그리고 그것이 당신을위한 옵션이라면 :
String[] places = {"Buenos Aires", "Córdoba", "La Plata"};
사소한 성능 차이를 신경 쓰지 않으면 배열을 Arraylist에 매우 간단하게 복사 할 수도 있습니다.
ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));
좋아, 그러나 앞으로는 장소 이름보다 조금 더 필요합니다. 국가 코드도 필요합니다. 이것이 여전히 런타임 중에는 변경되지 않는 미리 정의 된 목록이라고 가정하면 enum
미래에 목록을 변경 해야하는 경우 재 컴파일이 필요합니다.
enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}
될 것입니다 :
enum Places {
BUENOS_AIRES("Buenos Aires",123),
CORDOBA("Córdoba",456),
LA_PLATA("La Plata",789);
String name;
int code;
Places(String name, int code) {
this.name=name;
this.code=code;
}
}
열거는 정적입니다 values
방법이 선언 된 순서대로 열거의 모든 값을 포함하는 배열을 반환하는 방법 : 예 :
for (Places p:Places.values()) {
System.out.printf("The place %s has code %d%n",
p.name, p.code);
}
이 경우 Arraylist가 필요하지 않을 것 같습니다.
추신 랜디 아아가 시연했다 정적 유틸리티 방법을 사용하는 또 다른 좋은 방법 Collections.addall.
Java 9에는 다음과 같은 방법이 있습니다 불변 목록:
List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
필요한 경우 변동성 목록을 작성하도록 쉽게 조정됩니다.
List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
비슷한 방법을 사용할 수 있습니다 Set
그리고 Map
.
List<String> names = Arrays.asList("2","@2234","21","11");
당신이 사용할 수있는 StickyList
~에서 선인장:
List<String> names = new StickyList<>(
"Scott Fitzgerald", "Fyodor Dostoyevsky"
);
이 코드 라인을 사용해보십시오.
Collections.singletonList(provider)
예, 배열의 도움으로 배열 목록을 한 줄로 초기화 할 수 있습니다.
List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");
Java에서는 할 수 없습니다
ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
지적한 바와 같이, 당신은 더블 브레이스 초기화를 수행해야합니다.
List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};
그러나 이것은 당신이 주석을 추가하도록 강요 할 수 있습니다 @SuppressWarnings("serial")
또는 성가신 일련의 UUID를 생성하십시오. 또한 대부분의 Code Formatters는이를 여러 문/줄로 풀어줍니다.
또는 당신은 할 수 있습니다
List<String> places = Arrays.asList(new String[] {"x", "y" });
그러나 당신은 a를하고 싶을 수도 있습니다 @SuppressWarnings("unchecked")
.
또한 Javadoc에 따르면 다음을 수행 할 수 있어야합니다.
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
그러나 JDK 1.6으로 컴파일 할 수 없습니다.
Collections.singletonList(messageBody)
목록이 필요한 경우 하나의 항목!
컬렉션 출신입니다 java.util 패키지.
가장 좋은 방법 :
package main_package;
import java.util.ArrayList;
public class Stackkkk {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<Object>();
add(list, "1", "2", "3", "4", "5", "6");
System.out.println("I added " + list.size() + " element in one line");
}
public static void add(ArrayList<Object> list,Object...objects){
for(Object object:objects)
list.add(object);
}
}
원하는만큼의 요소를 가질 수있는 함수를 만들고 한 줄에 추가하도록 호출하십시오.
다음은 코드입니다 Abacusutil
// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
// The most efficient way, which is similar with Arrays.asList(...) in JDK.
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");
선언 : 저는 Abacusutil의 개발자입니다.
Me의 경우 Arrays.aslist ()는 최고이며 편리합니다. 나는 항상 그런 식으로 초기화하는 것을 좋아합니다. 당신이 Java 컬렉션의 초보자라면, 나는 당신이 참조하고 싶습니다 Arraylist 초기화
왜 이렇게하는 간단한 유틸리티 기능을 만들지 않겠습니까?
static <A> ArrayList<A> ll(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
"ll
""문자 목록 "을 나타냅니다.
ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
정적 컨텍스트 이전 경로에 저장된 XML 파일에서 MessagetemPlate 목록을 작성하고 있습니다.
public final class TemplateStore {
private TemplateStore(){}
private static final String [] VERSIONS = {"081"};
private static final String TEMPLATE_FILE_MASK = "template/EdiTemplates_v%s.xml";
private static final String ERROR = "Error In Building Edifact Message Template Store";
public static final List<MessageTemplate> TEMPLATE_LIST = Arrays.stream(VERSIONS)
.map(version -> TemplateStore.class
.getClassLoader().getResourceAsStream(String.format(TEMPLATE_FILE_MASK, version)))
.map(inputStream -> {
try {
return ((EdiTemplates) JAXBContext.newInstance(EdiTemplates.class).createUnmarshaller()
.unmarshal(inputStream)).getMessageTemplate();
} catch (JAXBException e) {
throw new IllegalArgumentException(ERROR, e);
}})
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
실제로 한 줄로 할 수 있습니다.
Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})