티스토리 뷰

JAVA

How to convert Arrays to List

seoca 2019. 2. 26. 01:39





1. Arrays.asList() method makes the original array available as a list. 



Example code

public class Main{
public static void main(String[] args) {
String[] fruit_array = new String[]{"apple","banana","mango"};
List<String> fruit_list = Arrays.asList(fruit_array);

//returned List is fixed size
fruit_list.add("melon"); //Error
fruit_list.remove(0); //Error

fruit_list.set(1,"kiwi");
System.out.println(fruit_list); //[apple, kiwi, mango]
}
}





2. Using List Constructor enables some kind of operations to change the List.



Example code

public class Main{
public static void main(String[] args) {
String[] fruit_array = new String[]{"apple","banana","mango"};
//Constructor
List<String> fruit_list = new ArrayList<>(Arrays.asList(fruit_array));

//you can do every operations on the List
fruit_list.add("melon");
fruit_list.remove(0);

fruit_list.set(1,"kiwi");
System.out.println(fruit_list); //[banana, kiwi, melon]
}
}





3. Collection API



Example code I

public class Main{
public static void main(String[] args) {
String[] fruit_array = new String[]{"apple","banana","mango"};

List<String> fruit_list = new ArrayList<>(fruit_array.length);
Collections.addAll(fruit_list,fruit_array);

System.out.println(fruit_list); //[apple, banana, mango]
}
}



Example code II

public class Main{
public static void main(String[] args) {
String[] fruit_array = new String[]{"apple","banana","mango"};

List<String> fruit_list = new ArrayList<>(Arrays.asList(fruit_array));
String[] another_array = new String[]{"add1","add2"};
Collections.addAll(fruit_list,another_array);

System.out.println(fruit_list); //[apple, banana, mango, add1, add2]
}
}



Reference

https://www.youtube.com/watch?v=_ntIzftXKMM


'JAVA' 카테고리의 다른 글

StringBuffer in Java  (0) 2019.03.05
Difference between Collection and Collections in Java  (0) 2019.02.26
Lambda Expression in Java  (0) 2019.02.22
compareTo method in Java  (0) 2019.02.21
Reference Data Type in Java  (0) 2019.02.20