Practical Examples of Array to ArrayList Conversion
Now that we've covered the different methods for converting an array to an ArrayList, let's look at some practical examples.
Example 1: Converting an Integer Array
// Convert an integer array to an ArrayList
int[] numbers = {1, 2, 3, 4, 5};
ArrayList<Integer> numberList = new ArrayList<>(Arrays.asList(numbers));
System.out.println(numberList); // Output: [1, 2, 3, 4, 5]
Example 2: Converting a String Array
// Convert a String array to an ArrayList
String[] fruits = {"Apple", "Banana", "Cherry"};
ArrayList<String> fruitList = new ArrayList<>(Arrays.asList(fruits));
System.out.println(fruitList); // Output: [Apple, Banana, Cherry]
Example 3: Converting a Custom Object Array
Let's define a simple Person
class:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters
}
Now, let's convert an array of Person
objects to an ArrayList:
// Convert an array of Person objects to an ArrayList
Person[] people = {
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35)
};
ArrayList<Person> personList = new ArrayList<>(Arrays.asList(people));
for (Person person : personList) {
System.out.println("Name: " + person.getName() + ", Age: " + person.getAge());
}
This will output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
These examples demonstrate how you can use the different methods discussed earlier to convert arrays of various data types to ArrayLists in Java. The choice of method will depend on your specific use case and personal preference.