티스토리 뷰
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으로 옮겨준다.
'JAVA' 카테고리의 다른 글
File I/O - Decorator pattern, File.separator (0) | 2019.07.05 |
---|---|
File I/O - loading data and creating txt file from CSV file. (0) | 2019.07.05 |
enum in Java (0) | 2019.06.24 |
Exception handling in Java (0) | 2019.06.24 |
Object type casting(upcasting,downcasting) example in Java (0) | 2019.06.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 프로그래머스
- Javascript Algorithm
- ... in Javascript
- spring boot application
- hackerrank solution
- compareTo()
- substring()
- Collection Framework
- easy algorithm
- repeat()
- hackerrank
- 프로그래머스 알고리즘
- rest parameter
- hackerrank javascript
- equals()
- java
- easy javascript algorithm
- 알고리즘
- javascript
- Object type casting
- algorithm
- C++
- HackerRank Algorithm
- 프로그래머스 알고리즘문제
- math.abs
- HashMap
- math.max
- hackerrank javascript solution
- string class in java
- code refactoring
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함