How to Convert an Java array into an Arraylist

 Posted On  | Yashwant Chavan 

Sample code To demonstrate the conversion of array T[] into ArrayList. Your underline object may String, Person or Any complex type. But while conversion you need to take care of big UnsupportedOperationException.

Person.java

This is the simple person Pojo class.

package com.technicalkeeda.bean;

public class Person {

 private String firstName;
 private String lastName;
 private String email;

 public Person() {

 }

 public Person(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;

 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

}

ConvertorTest.java

Below sample code convert an Array of Person into List of Person. One important thing I need to highlight here. The list returned from asList() has fixed size. So, if you try to add or remove elements from the returned list in your code or you are going to manipulate some operation on list, you'll need to wrap it in a new ArrayList(). Otherwise you'll get big an UnsupportedOperationException.

The list returned from asList is backed by the original array. If you modify the original array, the list will be modified as well.

package com.technicalkeeda.bean;

import java.util.Arrays;
import java.util.List;

public class ConvertorTest {
 public static void main(String[] args) {
  Person[] persons = { new Person("Yashwant", "Chavan", "XXX@gmail.com"),
    new Person("Mahesh", "Tawade", "YYY@gmail.com"),
    new Person("Suhas", "Lande", "ZZZ@gmail.com") };
  List personList = Arrays.asList(persons);
  for (Person person : personList) {
   System.out.println("Name:- " + person.getFirstName() + " "
     + person.getLastName());
  }
 }
}

UnsupportedOperationException

To overcome UnsupportedOperationException exception. You need put some extract efforts. Refer below code snippet.

List personList = new ArrayList(Arrays.asList(persons));

Finish :)

Hope you enjoy this article :) , In case if you any doubt please provide me you comments or questions.


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0357 seconds.