Java OCA OCP Practice Question 2394

Question

Consider this pre-generics implementation of method concat() in class MyString:.

class MyString {/*from  w  w  w  .ja  v  a  2 s. c  o  m*/
   public static String concat(List list) {                       //1
       String result = new String();                              //2
       for (Iterator iter = list.iterator(); iter.hasNext(); ) {  //3
           String value = (String)iter.next();                    //4
           result += value;                                       //5
       }
       return result;
   }
}

Which three of the following changes together will allow method concat() to be used with generics without generating unchecked warnings?.

  • a Replace line 1 with public static String concat(List<String> list) {.
  • b Replace line 1 with public static String concat(List<Integer> list) {.
  • c Remove code on line 3.
  • d Remove code on line 4.
  • e Change code on line 3 to for (String value : list) {.
  • f Change code on line 3 to for (String value : list.listIterator()) {.


a, d, e

Note

The options (a), (d), and (e), when implemented together, will allow method concat() to be used with generics without generating any warnings.

Option (b) is incorrect.

Replacing line 1 with public static String concat (List<Integer> list) { would generate a ClassCastException at runtime, if a list other than a list of integer objects is passed to method concat().

Option (c) is incorrect because a for loop is required to iterate through the list objects.

Options (d) and (e) are correct.

With generics, you can use an advanced for loop to iterate through list elements.

Because the object type is already specified (as String), the advanced for loop returns String objects, which don't require an explicit cast.

Option (f) is incorrect and won't compile.




PreviousNext

Related