Tutorialspoint
Problem
Solution
Submissions

Array to ArrayList

Certification: Basic Level Accuracy: 70% Submissions: 10 Points: 5

Write a Java program that demonstrates how to convert an Array to an ArrayList and vice versa. Implement methods that handle primitive arrays, object arrays, and perform the conversions efficiently.

Example 1
  • Input: Integer[] array = {1, 2, 3, 4, 5}
  • Output: ArrayList [1, 2, 3, 4, 5] and back to Array [1, 2, 3, 4, 5]
  • Explanation:
    • Convert Integer array to ArrayList
    • Then convert ArrayList back to array
    • Elements remain in same order in both conversions
Example 2
  • Input: String[] array = {"apple", "banana", "orange"}
  • Output: ArrayList [apple, banana, orange] and back to Array [apple, banana, orange]
  • Explanation:
    • Convert String array to ArrayList
    • Then convert back to original array format
    • Order and content are preserved
Constraints
  • 0 ≤ array.length ≤ 10^5
  • Array can be primitive or object type
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArrayseBayArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Arrays.asList() for quick conversion from array to ArrayList
  • Remember that Arrays.asList() creates a fixed-size list backed by the original array
  • For primitive arrays, you need to perform manual conversion or use wrapper classes
  • ArrayList's toArray() method can be used to convert back to an array
  • Consider using streams for more elegant solutions in Java 8+

Steps to solve by this approach:

 Step 1: For object arrays, use Arrays.asList() and pass it to ArrayList constructor.
 Step 2: For ArrayList to array conversion, use the toArray() method with an array of the proper type.
 Step 3: For primitive arrays like int[], create a special method that manually adds each element to the ArrayList.
 Step 4: When converting back to arrays, pass an empty array of the correct type to toArray().
 Step 5: Handle edge cases like null arrays and empty collections.
 Step 6: Consider using Java streams for more concise conversions in modern Java.
 Step 7: Test with different data types to ensure the generic methods work correctly.

Submitted Code :