Convert array to generic list with Java Reflections


An array can be converted into a fixed size list using the java.util.Arrays.asList() method. This method is basically a bridge between array based AP!’s and collection based API’s.

A program that demonstrates the conversion of an array into a generic list is given as follows −

Example

 Live Demo

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      String str[] = new String[]{"apple","orange","mango","guava", "melon"};
      List<String> list = Arrays.asList(str);
      System.out.println("The list is: " + list);
   }
}

The output of the above program is as follows −

The list is: [apple, orange, mango, guava, melon]

Now let us understand the above program.

First the string array str[] is defined. Then Arrays.asList() method is used to convert the array into a generic list. Finally this list is displayed. A code snippet which demonstrates this is as follows −

String str[] = new String[]{"apple","orange","mango","guava", "melon"};
List<String> list = Arrays.asList(str);
System.out.println("The list is: " + list);

Updated on: 25-Jun-2020

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements