Algorithm


Convert List to Array:

  1. Input:

    • List of elements (List myList), where T is the type of elements in the list.
  2. Algorithm:

    • Create an array of type T with a size equal to the size of the list.
    • Use the toArray() method of the List interface to copy elements from the list to the array.
  3. Pseudocode:

    java
    List myList = // input list
    T[] myArray = myList.toArray(new T[myList.size()]);

Convert Array to List:

  1. Input:

    • Array of elements (T[] myArray), where T is the type of elements in the array.
  2. 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.
  3. 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

x
+
cmd
List: [Java, Python, JavaScript]
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

x
+
cmd
Array: [Java, Python, C]
List: [Java, Python, C]
Advertisements

Demonstration


Java Programing Example to Convert a List to Array and Vice Versa-DevsEnv