programing

Java에서 새 목록을 만드는 방법

copysource 2022. 7. 10. 11:14
반응형

Java에서 새 목록을 만드는 방법

we a a a a a a를 만듭니다.Set같이요.

Set myset = new HashSet()

「 」를 작성하려면 해야 ?List★★★★★★★★★★★★★★★★★?

List myList = new ArrayList();

또는 제네릭(Java 7 이후)을 사용합니다.

List<MyType> myList = new ArrayList<>();

또는 범용(구 Java 버전)을 사용합니다.

List<MyType> myList = new ArrayList<MyType>();

또한 항목이 들어 있는 목록을 만드는 경우(단, 크기가 고정되어 있음)

List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");

요약해서 덧붙이겠습니다.

JDK

1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")

구아바

1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

불변의 리스트

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

빈 불변 리스트

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

캐릭터 목록

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

정수 목록

Ints.asList(1,2,3);                                             // Guava

Java 8의 경우

비어 있지 않은 고정 크기 목록을 작성하려면(추가, 제거 등의 작업은 지원되지 않음)

List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported

비어 있지 않은 변환 가능 목록을 작성하려면:

List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));

Java 9의 경우

새로운 스태틱팩토리 방식 사용:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

Java 10의 경우

로컬 변수 유형 추론 사용:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

베스트 프랙티스를 따르세요.

원시 유형 사용 안 함

Java 5 이후 제네릭은 언어의 일부가 되었습니다.사용자는 다음과 같이 사용할 필요가 있습니다.

List<String> list = new ArrayList<>(); // Good, List of String

List list = new ArrayList(); // Bad, don't do that!

인터페이스로의 프로그램

를 들어, 프로그램 할 때, 프로그램 할 때, for for for 、 로 、 로 、 로 、 for 、 。List★★★★★★★★★★★★★★★★★★:

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

대신:

ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!

먼저 이걸 읽고 그다음에 이거랑 이거를 읽어보세요.10번 중 9번은 이 두 가지 구현 중 하나를 사용합니다.

Sun's Guide to the Collections 프레임워크를 읽어보십시오.

Java 7에서는 범용 인스턴스 작성에 대한 유형 추론이 있기 때문에 할당 오른쪽에 범용 파라미터를 복제할 필요가 없습니다.

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

고정 크기 목록은 다음과 같이 정의할 수 있습니다.

List<String> list = Arrays.asList("foo", "bar");

불변 목록의 경우 Guava 라이브러리를 사용할 수 있습니다.

List<String> list = ImmutableList.of("foo", "bar");
//simple example creating a list form a string array

String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};

List mylist = Arrays.asList(myStrings );

//getting an iterator object to browse list items

Iterator itr= mylist.iterator();

System.out.println("Displaying List Elements,");

while(itr.hasNext())

  System.out.println(itr.next());

리스트는 Set과 같은 인터페이스입니다.

HashSet이 퍼포먼스를 추가/검색/삭제하기 위한 특정 속성을 가진 세트의 구현인 것처럼 ArrayList는 목록의 구현입니다.

각 인터페이스의 메뉴얼을 참조하면, 「All Known Implementing Classes(모든 기존의 실장 클래스)」를 참조할 수 있습니다.또, 어느 것이 요구에 적합한지를 판단할 수 있습니다.

Array List일 가능성이 높습니다.

List는 인터페이스입니다.Set 가지고 있습니다.ArrayList ★★★★★★★★★★★★★★★★★」LinkedList일반적인 목적의 실장으로서.

리스트는 다음과 같이 작성할 수 있습니다.

 List<String> arrayList = new ArrayList<>();
 List<String> linkedList = new LinkedList<>(); 

다음과 같은 고정 크기 목록을 만들 수도 있습니다.

List<String> list = Arrays.asList("A", "B", "C");

우리는 거의 항상 다음을 사용하고 있을 것이다.ArrayList에 서다LinkedList★★★★

  1. LinkedList객체에 많은 공간을 사용하고 요소가 많으면 성능이 저하됩니다.
  2. LinkedList에O( 시간이합니다.ArrayList.
  3. 자세한 내용은 이 링크를 참조하십시오.

에 의해 Arrays.asList위의 요소는 구조적으로 수정할 수 없지만 해당 요소는 수정할 수 있습니다.

자바 8

doc에 따르면 방법은Collections.unmodifiableList지정된 목록의 변경할 수 없는 보기를 반환합니다.을 사용하다

Collections.unmodifiableList(Arrays.asList("A", "B", "C"));

자바 9

Java 9를 사용하는 경우:

List<String> list = List.of("A", "B");

자바 10

'10'은 '10'입니다.Collectors.unmodifiableList는 Java 9에서 도입된 완전히 수정할 수 없는 목록의 인스턴스를 반환합니다.의 차이에 대한 자세한 내용은 다음 답변을 참조하십시오.Collections.unmodifiableList »Collectors.unmodifiableListJava 10으로 설정합니다.

List list = new ArrayList();

또는 제네릭으로

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

물론 문자열을 Integer와 같은 모든 유형의 변수로 바꿀 수도 있습니다.

java의 배열 목록 선언은 다음과 같습니다.

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Java에서 어레이 목록을 만들고 초기화할 수 있는 방법은 여러 가지가 있습니다.

 1) List list = new ArrayList();

 2) List<type> myList = new ArrayList<>();

 3) List<type> myList = new ArrayList<type>();

 4) Using Utility class

    List<Integer> list = Arrays.asList(8, 4);
    Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

 5) Using static factory method

    List<Integer> immutableList = List.of(1, 2);


 6) Creation and initializing at a time

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});



 Again you can create different types of list. All has their own characteristics

 List a = new ArrayList();
 List b = new LinkedList();
 List c = new Vector(); 
 List d = new Stack(); 
 List e = new CopyOnWriteArrayList();

다음은 목록을 작성할 수 있는 몇 가지 방법입니다.

  • 이렇게 하면 고정된 크기의 목록이 생성됩니다. 요소를 추가/제거할 수 없습니다. 이 작업을 수행하면,java.lang.UnsupportedOperationException그렇게 하려고 하면.
    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
    List<String> fixedSizeList = Arrays.asList("Male", "Female");
    List<String> fixedSizeList = List.of("Male", "Female"); //from java9

  • 다음 버전은 원하는 수의 요소를 추가하거나 제거할 수 있는 간단한 목록입니다.

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

  • '만들다'를 수 .LinkedList 삽입해야 할 java를 해야 .LinkedListArrayList

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

새로운 Array List가 아닌 새로운 Linked List가 필요할 수 있습니다.먼저 Array List에서 시작하여 성능상의 문제가 있고 목록에 많은 추가 및 삭제가 이루어지고 있는 경우(이전에는 해당되지 않음) Linked List로 전환하여 상황이 개선되는지 확인합니다.그러나 기본적으로 Array List를 유지하면 모든 것이 정상입니다.

한 가지 예:

List somelist = new ArrayList();

javadoc for List를 참조하여 이미 알려진 모든 구현 클래스를 찾을 수 있습니다.Listapi.api에 입니다.

Google 컬렉션을 사용하면 목록 클래스에서 다음 방법을 사용할 수 있습니다.

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

및 vararargs .Iterable<T>

이러한 메서드의 장점은 컨스트럭터처럼 범용 파라미터를 명시적으로 지정할 필요가 없다는 것입니다.컴파일러는 변수의 유형에서 이를 추론합니다.

Java 8에서 동일한 작업을 수행할 수 있는 더 많은 옵션, 더 나은 옵션, 더 나쁜 옵션, 더 나은 옵션, 다른 옵션, 목록으로 추가 작업을 수행할 경우 Streams에서 더 많은 대안(필터링, 매핑, 축소 등)을 제공합니다.

List<String> listA = Stream.of("a", "B", "C").collect(Collectors.toList());
List<Integer> listB = IntStream.range(10, 20).boxed().collect(Collectors.toList());
List<Double> listC = DoubleStream.generate(() -> { return new Random().nextDouble(); }).limit(10).boxed().collect(Collectors.toList());
LinkedList<Integer> listD = Stream.iterate(0, x -> x++).limit(10).collect(Collectors.toCollection(LinkedList::new));

옵션으로서 여기서 더블 브레이스 초기화를 사용할 수 있습니다.

List<String> list = new ArrayList<String>(){
  {
   add("a");
   add("b");
  }
};
List<Object> nameOfList = new ArrayList<Object>();

Import가 필요합니다.List그리고.ArrayList.

Java 9 에서는, 다음의 조작을 실시해, 불변의 설정을 작성할 수 있습니다. List:

List<Integer> immutableList = List.of(1, 2, 3, 4, 5);

List<Integer> mutableList = new ArrayList<>(immutableList);

세트 및 목록을 작성하는 방법은 여러 가지가 있습니다.HashSet과 ArrayList는 두 가지 예입니다.최근에는 제네릭스를 컬렉션과 함께 사용하는 것도 꽤 흔하다.이게 뭔지 한번 봐주셨으면 합니다.

이것은 Java의 빌트인 컬렉션에 대한 좋은 소개입니다.http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html

List arrList = new ArrayList();

다음과 같이 제네릭을 사용하는 것이 좋습니다.

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

arrList.add("one");

Linked List를 사용하는 경우.

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

Eclipse 컬렉션을 사용하여 다음과 같은 목록을 만들 수 있습니다.

List<String> list1 = Lists.mutable.empty();
List<String> list2 = Lists.mutable.of("One", "Two", "Three");

변경할 수 없는 목록을 원하는 경우:

ImmutableList<String> list3 = Lists.immutable.empty();
ImmutableList<String> list4 = Lists.immutable.of("One", "Two", "Three");

기본 목록을 사용하면 자동 상자를 사용하지 않아도 됩니다.int 목록을 작성하는 방법은 다음과 같습니다.

MutableIntList list5 = IntLists.mutable.empty();
MutableIntList list6 = IntLists.mutable.of(1, 2, 3);

ImmutableIntList list7 = IntLists.immutable.empty();
ImmutableIntList list8 = IntLists.immutable.of(1, 2, 3);

8개의 모든 기본 요소에는 변형이 있습니다.

MutableLongList longList       = LongLists.mutable.of(1L, 2L, 3L);
MutableCharList charList       = CharLists.mutable.of('a', 'b', 'c');
MutableShortList shortList     = ShortLists.mutable.of((short) 1, (short) 2, (short) 3);
MutableByteList byteList       = ByteLists.mutable.of((byte) 1, (byte) 2, (byte) 3);
MutableBooleanList booleanList = BooleanLists.mutable.of(true, false);
MutableFloatList floatList     = FloatLists.mutable.of(1.0f, 2.0f, 3.0f);
MutableDoubleList doubleList   = DoubleLists.mutable.of(1.0, 2.0, 3.0);

주의: 저는 Eclipse Collections의 커밋입니다.

이것을 시험해 보세요.

List<String> messages = Arrays.asList("bla1", "bla2", "bla3");

또는 다음 중 하나를 선택합니다.

List<String> list1 = Lists.mutable.empty(); // Empty
List<String> list2 = Lists.mutable.of("One", "Two", "Three");

단일 엔티티로 시리얼 가능한 불변 리스트가 필요한 경우 다음을 사용할 수 있습니다.

List<String> singList = Collections.singletonList("stackoverlow");

목록은 다양한 방법으로 작성할 수 있습니다.

1 - 컨스트럭터 초기화

List는 인터페이스이며 List의 인스턴스는 다음과 같은 방법으로 작성할 수 있습니다.

List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();

2- Arrays.asList() 사용

List<Integer> list=Arrays.asList(1, 2, 3);

3- 컬렉션 클래스의 메서드를 사용합니다.

빈 목록

List<Integer> list = Collections.EMPTY_LIST;

또는

List<Integer> list = Collections.emptyList();

Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);

수정할 수 없는 목록

List<Integer> list = Collections
        .unmodifiableList(Arrays.asList(1, 2, 3));

싱글턴 리스트

List<Integer> list = Collections.singletonList(2);

자세한 내용은 아래 참조 링크를 참조하십시오.

레퍼런스:

https://www.geeksforgeeks.org/initializing-a-list-in-java/

언급URL : https://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java

반응형