I usually need to convert Array object to List object and vice versa in my company project. So, I write this tutorial to share to you all how I can do that.
In this tutorial, I use Array and List object with type of String object. For other type non String object, you can do the same.
The first thing, we will look at how we can convert an List object to Array object. Maybe, you only need see the code as below to know how you can do this.
1 2 3 4 5 6 7 |
List<String> s = new ArrayList<String>(); s.add("John"); s.add("Jame"); String[] arr = s.toArray(new String[s.size()]); System.err.println(arr[0]); |
Result:
Converting from Array object to List object is easier. In Java, we have a static method asList() in Arrays object allow us can convert from Array object to List object quickly and easily.
Let look at the example as below:
1 2 3 4 5 |
String[] arr = { "John", "Jame" }; List<String> s = Arrays.asList(arr); System.err.println(s.get(1)); |
Result: