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