programing

Java에서 List 개체를 초기화하려면 어떻게 해야 합니까?

prostudy 2022. 8. 31. 21:48
반응형

Java에서 List 개체를 초기화하려면 어떻게 해야 합니까?

다음 코드와 같이 목록을 초기화할 수 없습니다.

List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));

다음과 같은 오류가 발생합니다.

할 수 없습니다.List<String>

「 」를 인스턴스화하려면 해야 합니까?List<String>

API를 체크하면List하다

Interface List<E>

가 being being interface수 「no」 「no」 「no」).new List()가능합니다).

「 」라고 이 표시됩니다.class 를 실장하고 .List:

이미 알려진 모든 구현 클래스:

AbstractList,AbstractSequentialList,ArrayList,AttributeList,CopyOnWriteArrayList,LinkedList,RoleList,RoleUnresolvedList,Stack,Vector

이들 중 일부는 인스턴스화할 수 있습니다(이것들은 다음과 같이 정의되지 않습니다).abstract class링크를 사용하여 자세한 내용을 확인하십시오.E: 어떤 것이 당신의 요구에 더 적합한지 알아야 합니다.

가장 일반적으로 사용되는 3가지 항목은 다음과 같습니다.

 List<String> supplierNames1 = new ArrayList<String>();
 List<String> supplierNames2 = new LinkedList<String>();
 List<String> supplierNames3 = new Vector<String>();

너스: :
, 쉽게, 보다 쉽게, 쉽게, 가치로 할 수 .Arrays class음음음같 뭇매하다

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));

이 에는 더 할 수 .fixed-size.

인터페이스를 인스턴스화할 수 없지만 구현이 거의 없습니다.

JDK2

List<String> list = Arrays.asList("one", "two", "three");

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

// creates immutable lists, so you can't modify such list 
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list 
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));

게다가 Guava와 같은 다른 도서관에서 제공하는 많은 방법들이 있다.

List<String> list = Lists.newArrayList("one", "two", "three");

리스트는 인터페이스입니다.인터페이스는 규칙이기 때문에 어떤 메서드에 클래스가 있어야 하는지 인터페이스를 인스턴스화할 수 없습니다.인스턴스화하려면 해당 인터페이스의 실현(실장)이 필요합니다.List 인터페이스의 일반적인 실장에서는, 다음의 코드를 사용해 주세요.

List<String> supplierNames = new ArrayList<String>(); 

또는

List<String> supplierNames = new LinkedList<String>();

하다를 .ArrayList<String>그런 것 같아요.

List<String>을 사용하다

사용방법:

import java.util.ArrayList;

...

List<String> supplierNames = new ArrayList<String>();

List는 인터페이스이므로 인터페이스를 초기화할 수 없습니다.대신 구현 클래스를 인스턴스화하십시오.

예를 들어 다음과 같습니다.

List<String> abc = new ArrayList<String>();
List<String> xyz = new LinkedList<String>();

심플한 것이 .ArrayList - ★★★★★★★★★★★★★★★★★」List

JDK 버전7 이전

List<String> list = new ArrayList<String>();

JDK 7 이상에서는 다이아몬드 연산자를 사용할 수 있습니다.

List<String> list = new ArrayList<>();

자세한 내용은 Oracle 문서 - 컬렉션에 기재되어 있습니다.

리스트는 인터페이스일 뿐이며, 일반적인 리스트의 정의입니다.이 리스트 인터페이스의 실장을 제공할 필요가 있습니다.가장 일반적인 것은 다음 두 가지입니다.

Array List - 어레이에 구현된 목록

List<String> supplierNames = new ArrayList<String>();

Linked List - 요소의 상호 연결된 체인처럼 구현된 목록

List<String> supplierNames = new LinkedList<String>();

사용하는 목록의 종류에 따라 다음과 같은 것이 있습니다.

List<String> supplierNames = new ArrayList<String>();

널 풀어줄 수 있을 거야.

List는 인터페이스, ArrayList는 List 인터페이스의 1가지 구현입니다.List 인터페이스의 JavaDocs를 읽으면 사용자의 요구에 더 적합한 구현을 찾을 수 있습니다.

만약 당신이 불변의 것을 만들고 싶다면 List<T>오브젝트가1개만 있으면 다음 API를 사용할 수 있습니다.

List<String> oneObjectList = Collections.singletonList("theOnlyObject”);

상세정보: 문서

리스트는 인터페이스입니다.목록을 사용하여 초기화할 수 없습니다.

  List<String> supplierNames = new ArrayList<String>();

이것들은 리스트의 보충된 클래스입니다.

ArrayList, LinkedList, Vector

필요에 따라 이 중 하나를 사용할 수 있습니다.각 클래스에는 고유한 기능이 있습니다.

혹시 모르니까 이 질문에서 맴도는 사람이 있어요.왜냐하면, 한 두 명의 새로운 사용자가 다시 같은 질문을 던지고 모두가 "아니요, Prudence님, 여기 제시된 모든 답변과는 별도로, 는 추가 정보를 제공하고 싶습니다. List = new List(); 단, 모든 인터페이스 메서드의 구현에 대한 비용을 지불해야 합니다.이 개념은 단순히 List = new List()가 아닙니다.

List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }

..... 등 (모든 방법을 기입해 주세요.)

이것은 Anonymous 클래스의 입니다.누군가가 "아니요, 인터페이스를 인스턴스화할 수 없습니다."라고 했을 때 맞습니다.그러나 "You CANT write List = new List()"라고는 말할 수 없습니다.그러나 분명히 당신은 그렇게 할 수 있고 당신은 그렇게 할 수 없습니다.

대신:

List<String> supplierNames = new List<String>();

최신 JDK 를 사용하고 있는 경우는, 다음과 같이 기입해 주세요.

 List<String> supplierNames = new ArrayList<>();

이것이 목록을 초기화하는 올바른 방법입니다.

우리는 하나의 문제를 단순화하기 위해 소유즈(soyuz-)를 만들었습니다: 변환 방법X로.Y(예:String로.Integer오브젝트 작성도 변환의 일종이기 때문에 간단한 작성 기능을 가지고 있습니다.Map,List,Set:

import io.thedocs.soyuz.to;

List<String> names = to.list("John", "Fedor");

확인해 주세요.다른 유용한 기능이 많이 있습니다.

언급URL : https://stackoverflow.com/questions/13395114/how-to-initialize-liststring-object-in-java

반응형