JAVA
Convert Array to ArrayList, ArrayList to Set
seoca
2019. 7. 1. 14:10
asList() is used to convert Array to List.
This example takes an Integer type array as a parameter and it needs to remove duplicate numbers as a result.
But, when you use asList(), the type of array should be Object type wrappers.
Because Generics only works for a reference type.
List<E> 는 Generic 이기에 오직 reference type만을 전달 받는다. 그래서 asList()에 primitive 타입이 올 수 없게 된다.
Example Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Integer[] arrayInt = {1, 2, 3, 3, 5, 5, 6, 3};
sort(arrayInt);
int[] arr = {1, 2, 3, 3, 5, 5, 6, 3};
sort2(arr);
}
//Reference type Array
public static void sort(Integer[] arr) {
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(arr));
for (Integer integer : set) {
System.out.print(integer + " "); //1 2 3 5 6
}
System.out.println("");
}
//Primitive type Array
public static void sort2(int[] arr) {
List<Integer> list = new ArrayList<>();
for(int i : arr){
list.add(i);
}
Set<Integer> set = new LinkedHashSet<>(list);
for (Integer integer : set) {
System.out.print(integer + " "); //1 2 3 5 6
}
}
}
|
If it's primitive type Array, we need 'for loop'
만일 primitive type의 array를 set으로 변환하려면 ArrayList를 for loop으로 돌려서 list에 담아주고 그것을 다시 set으로 옮겨준다.