Algorithm
Convert List to Array:
-
Input:
- List of elements (
List myList
), whereT
is the type of elements in the list.
- List of elements (
-
Algorithm:
- Create an array of type
T
with a size equal to the size of the list. - Use the
toArray()
method of theList
interface to copy elements from the list to the array.
- Create an array of type
-
Pseudocode:
java
List myList = // input list T[] myArray = myList.toArray(new T[myList.size()]);
Convert Array to List:
-
Input:
- Array of elements (
T[] myArray
), whereT
is the type of elements in the array.
- Array of elements (
-
Algorithm:
- Use the
Arrays.asList()
method to convert the array to a fixed-size list. - If you need a modifiable list, create a new
ArrayList
and add elements from the array.
- Use the
-
Pseudocode:
java
T[] myArray = // input array List myList = new ArrayList<>(Arrays.asList(myArray));
These algorithms assume that you are working with non-primitive types. If you are working with primitive types, you may need to use wrapper classes (e.g., Integer
for int
, Double
for double
, etc.) or consider using specialized libraries like Apache Commons Lang or Guava for primitive collections.
Code Examples
#1 Code Example- Convert the Java List into Array
Code -
Java Programming
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList languages = new ArrayList < >();
// Add elements in the list
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
System.out.println("ArrayList: " + languages);
// Create a new array of String type
String[] arr = new String[languages.size()];
// Convert ArrayList into the string array
languages.toArray(arr);
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
}
}
}
Copy The Code &
Try With Live Editor
Output
Array: Java, Python, JavaScript,
#2 Code Example- Convert Java Array to List
Code -
Java Programming
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) {
// create an array
String[] array = {"Java", "Python", "C"};
System.out.println("Array: " + Arrays.toString(array));
// convert array to list
List languages= new ArrayList < >(Arrays.asList(array));
System.out.println("List: " + languages);
}
}
Copy The Code &
Try With Live Editor
Output
List: [Java, Python, C]
Demonstration
Java Programing Example to Convert a List to Array and Vice Versa-DevsEnv