Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Study the following program and figure out the error in program. How can you fix

ID: 3536414 • Letter: S

Question

Study the following program and figure out the error in program. How can you fix it?

1.        import java.util.ArrayList;

2.        import java.util.Collections;

3.        import java.util.List;

4.        import java.util.Arrays;

5.       

6.        /*

7.        Java String Array To List Example

8.        This Java String Array To List Example shows how to convert Java String array to java.util.List object

9.        using Arrays.asList method.

10.     */

11.     public JavaStringArrayToListExample {

12.    

13.     public static void main(String args[]){

14.    

15.     //create String array

16.     String[] numbers = new String[]{"one", "two", "three"};

17.    

18.     /*

19.     * To covert String array to java.util.List object, use

20.     * List asList(String[] strArray) method of Arrays class.

21.     */

22.    

23.     List list = (List) Arrays.asList(numbers);

24.    

25.     //display elements of List

26.     System.out.println("String array converted to List");

27.     for(int i=0; i < list.size(); i++){

28.     System.out.println(list.get(i));

29.     }

30.    

31.     /*

32.     * Please note that list object created this way can not be modified.

33.     * Any attempt to call add or delete method would throw UnsupportedOperationException exception.

34.     *

35.     * If you want modifiable list object, then use

36.     *

37.     * ArrayList list = (ArrayList) Arrays.asList(numbers);

38.     */

39.    

40.     /* Alternate Method to covert String array to List */

41.     List anotherList = new ArrayList();

42.    

43.     Collections.addAll(anotherList, numbers);

44.     }

45.     }

46.    

47.     /*

48.     Output of this example would be

49.     String array converted to List

50.     one

51.     two

52.     three

53.     */

Explanation / Answer

Actually, this compiles and runs fine.