Conversion Techniques
Array to List Conversion Methods
1. Using Arrays.asList() Method
import java.util.Arrays;
import java.util.List;
public class ArrayToListConversion {
public static void main(String[] args) {
// Primitive array conversion
Integer[] intArray = {1, 2, 3, 4, 5};
List<Integer> intList = Arrays.asList(intArray);
}
}
2. Using ArrayList Constructor
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListConversionTechniques {
public static void main(String[] args) {
// Primitive array to ArrayList
Integer[] originalArray = {1, 2, 3, 4, 5};
List<Integer> arrayList = new ArrayList<>(Arrays.asList(originalArray));
}
}
List to Array Conversion Methods
1. Using toArray() Method
import java.util.ArrayList;
import java.util.List;
public class ListToArrayConversion {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
// Convert List to Array
String[] stringArray = stringList.toArray(new String[0]);
}
}
Conversion Techniques Comparison
graph TD
A[Conversion Techniques] --> B[Array to List]
A --> C[List to Array]
B --> D[Arrays.asList()]
B --> E[ArrayList Constructor]
C --> F[toArray() Method]
Conversion Considerations
Conversion Type |
Method |
Pros |
Cons |
Array to List |
Arrays.asList() |
Simple |
Fixed-size list |
Array to List |
New ArrayList |
Mutable list |
Slightly more verbose |
List to Array |
toArray() |
Flexible |
Requires type specification |
Handling Primitive Types
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PrimitiveConversion {
public static void main(String[] args) {
// Primitive int array to List
int[] primitiveArray = {1, 2, 3, 4, 5};
List<Integer> intList = Arrays.stream(primitiveArray).boxed().collect(Collectors.toList());
// List to primitive array
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5);
int[] backToPrimitiveArray = numberList.stream().mapToInt(Integer::intValue).toArray();
}
}
Arrays.asList()
creates a fixed-size list
- Using
new ArrayList<>()
provides a mutable list
- Stream-based conversions offer more flexibility but may have slight performance overhead
At LabEx, we recommend choosing the most appropriate conversion technique based on your specific use case and performance requirements.