Java로 새 목록을 만드는 방법
다음 Set
과 같이 생성합니다 .
Set myset = new HashSet()
List
Java로 어떻게 생성 합니까?
List myList = new ArrayList();
또는 제네릭 ( Java 7 이상)
List<MyType> myList = new ArrayList<>();
또는 제네릭 (이전 자바 버전)
List<MyType> myList = new ArrayList<MyType>();
추가로, 목록이 포함 된 목록을 만들려면 (크기는 고정되어 있지만) :
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
요약하고 추가하겠습니다.
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.of(...)
정적 팩토리 메소드 사용 :
List<Integer> immutableList = List.of(1, 2);
List<Integer> mutableList = new ArrayList<>(List.of(3, 4));
Java 10에서
은 Using 지역 변수 유형 추론을 :
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!
인터페이스 프로그램
예를 들어 다음과 같은 List
인터페이스를 프로그래밍합니다 .
List<Double> list = new ArrayList<>();
대신에:
ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!
먼저 이것을 읽은 다음 이것 과 이것을 읽으십시오 . 10 번 중 9 번은이 두 가지 구현 중 하나를 사용합니다.
사실 Sun의 Collections 프레임 워크 가이드를 읽으십시오 .
//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());
Java 7부터는 일반 인스턴스 생성에 대한 유형 추론이 있으므로 할당 오른쪽에 일반 매개 변수를 복제 할 필요가 없습니다.
List<String> list = new ArrayList<>();
고정 크기 목록은 다음과 같이 정의 할 수 있습니다.
List<String> list = Arrays.asList("foo", "bar");
변경 불가능한 목록의 경우 Guava 라이브러리를 사용할 수 있습니다 .
List<String> list = ImmutableList.of("foo", "bar");
Like HashSet is an implementation of a Set which has certain properties in regards to add / lookup / remove performance, ArrayList is the bare implementation of a List.
If you have a look at the documentation for the respective interfaces you will find "All Known Implementing Classes" and you can decide which one is more suitable for your needs.
Chances are that it's ArrayList.
List
is an interface like Set
and has ArrayList
and LinkedList
as general purpose implementations.
We can create List as:
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
We can also create a fixed-size list as:
List<String> list = Arrays.asList("A", "B", "C");
We would almost always be using ArrayList
opposed to LinkedList
implementation:
LinkedList
uses a lot of space for objects and performs badly when we have lots of elements.- Any indexed operation in
LinkedList
requires O(n) time compared to O(1) inArrayList
. - Check this link for more information.
The list created by Arrays.asList
above can not be modified structurally but its elements can still be modified.
Java 8
As per doc, the method Collections.unmodifiableList
returns an unmodifiable view of the specified list. We can get it like:
Collections.unmodifiableList(Arrays.asList("A", "B", "C"));
Java 9
In case we are using Java 9 then:
List<String> list = List.of("A", "B");
Java 10
In case we are at Java 10 then the method Collectors.unmodifiableList
will return an instance of truly unmodifiable list introduced in Java 9. Check this answer for more info about the difference in Collections.unmodifiableList
vs Collectors.unmodifiableList
in Java 10.
List list = new ArrayList();
Or with generics
List<String> list = new ArrayList<String>();
You can, of course, replace string with any type of variable, such as Integer, also.
Sometimes - but only very rarely - instead of a new ArrayList, you may want a new LinkedList. Start out with ArrayList and if you have performance problems and evidence that the list is the problem, and a lot of adding and deleting to that list - then - not before - switch to a LinkedList and see if things improve. But in the main, stick with ArrayList and all will be fine.
One example:
List somelist = new ArrayList();
You can look at the javadoc for List and find all known implementing classes of the List
interface that are included with the java api.
Using Google Collections, you could use the following methods in the Lists class
import com.google.common.collect.Lists;
// ...
List<String> strings = Lists.newArrayList();
List<Integer> integers = Lists.newLinkedList();
There are overloads for varargs initialization and initialising from an Iterable<T>
.
The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable.
List<Object> nameOfList = new ArrayList<Object>();
You need to import List
and ArrayList
.
With Java 9, you are able to do the following to create an immutable List
:
List<Integer> immutableList = List.of(1, 2, 3, 4, 5);
List<Integer> mutableList = new ArrayList<>(immutableList);
As an option you can use double brace initialization here:
List<String> list = new ArrayList<String>(){
{
add("a");
add("b");
}
};
There are many ways to create a Set and a List. HashSet and ArrayList are just two examples. It is also fairly common to use generics with collections these days. I suggest you have a look at what they are
This is a good introduction for java's builtin collections. http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html
List arrList = new ArrayList();
Its better you use generics as suggested below:
List<String> arrList = new ArrayList<String>();
arrList.add("one");
Incase you use LinkedList.
List<String> lnkList = new LinkedList<String>();
More options to do the same thing with Java 8, not better, not worse, just different and if you want to do some extra work with the lists, Streams will provide you more alternatives (filter, map, reduce, etc.)
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));
Using Eclipse Collections you can create a List like this:
List<String> list1 = Lists.mutable.empty();
List<String> list2 = Lists.mutable.of("One", "Two", "Three");
If you want an immutable list:
ImmutableList<String> list3 = Lists.immutable.empty();
ImmutableList<String> list4 = Lists.immutable.of("One", "Two", "Three");
You can avoid auto-boxing by using primitive lists. Here's how you'd create int lists:
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);
There are variants for all 8 primitives.
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);
Note: I am a committer for Eclipse Collections.
The following are some ways you can create lists.
This will create a list with fixed size, adding/removing elements is not possible, it will throw a
java.lang.UnsupportedOperationException
if you try to do so.List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
The following version is a simple list where you can add/remove any number of elements.
List<String> list = new ArrayList<>();
This is how to create a
LinkedList
in java, If you need to do frequent insertion/deletion of elements on the list, you should useLinkedList
instead ofArrayList
List<String> linkedList = new LinkedList<>();
Try this:
List<String> messages = Arrays.asList("bla1", "bla2", "bla3");
Or:
List<String> list1 = Lists.mutable.empty(); // Empty
List<String> list2 = Lists.mutable.of("One", "Two", "Three");
If you need a serializable, immutable list with a single entity you can use:
List<String> singList = Collections.singletonList("stackoverlow");
As declaration of array list in java is like
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
There is numerous way you can create and initialize array list in 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();
참고URL : https://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java
'development' 카테고리의 다른 글
개체의 속성을 기반으로 개체 목록을 정렬하는 방법은 무엇입니까? (0) | 2020.09.30 |
---|---|
JavaScript 배열에서 임의의 값 가져 오기 (0) | 2020.09.30 |
jQuery를 사용하여 이미지 소스 변경 (0) | 2020.09.30 |
HTML 페이지에서 스크롤 막대 숨기기 (0) | 2020.09.30 |
Java에서 파일을 byte []로 (0) | 2020.09.30 |