Java OCA OCP Practice Question 2328

Question

The class java.lang.String implements the interface java.lang.CharSequence.

Given the following code:

public class Main {
  public static void main(String[] args) {
    List<String> lst = Arrays.asList("Java", "only", "promotes", "fun");
    Collection<String> resultList = delete4LetterWords(lst);
  }//  w ww. jav a 2  s.  co  m

  // (1) INSERT METHOD HEADER HERE
  {
    Collection<E> permittedWords = new ArrayList<E>();
    for (E word : words) {
      if (word.length() != 4) permittedWords.add(word);
    }
    return permittedWords;
  }
}

Which method header can be inserted at (1) so that the program compiles and runs without errors?.

Select the one correct answer.

(a) static <E extends CharSequence> Collection<? extends CharSequence>
    delete4LetterWords(Collection<E> words)
(b) static <E extends CharSequence> List<E>
    delete4LetterWords(Collection<E> words)
(c) static <E extends CharSequence> Collection<E>
    delete4LetterWords(Collection<? extends CharSequence> words)
(d) static <E extends CharSequence> List<E>
    delete4LetterWords(Collection<? extends CharSequence> words)
(e) static <E extends CharSequence> Collection<E>
    delete4LetterWords(Collection<E> words)
(f) public <E super CharSequence> Collection<E>
    delete4LetterWords(Collection<E> words)


(e)

Note

(a) Incompatible types for assignment in the main() method: cannot convert from Collection<capture-of ? extends CharSequence> to Collection<String>.

(b) Incompatible return value in the delete4LetterWords() method: cannot convert from Collection<E> to List<E>.

(c) In the for(:) loop, the component type of words (capture-of ? CharSequence) cannot be converted to E.

(d) In the for(:) loop, the component type of words (capture-of ? CharSequence) cannot be converted to E. Incompatible return value in the delete4LetterWords() method: cannot convert from Collection<E> to List<E>.

(e) OK.

(f) Keyword super cannot be used in a constraint. It can only be used with a wildcard (?).




PreviousNext

Related