About Question com.enthuware.ets.scjp.v6.2.97 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Daan Debie

About Question com.enthuware.ets.scjp.v6.2.97 :

Post by Daan Debie »

In my answer I used ArrayList as return type, like this:

Code: Select all

public < E  extends CharSequence > ArrayList < E >
	    getWordsStartingWith( Collection< E > input , char ch )
    {
        ArrayList<  E  > returnValue = new ArrayList< E >();
	int len = input.size();
	for(E e : input)
	{
	    if(e.charAt(0) == ch) returnValue.add(e);
	}
	return returnValue;
    }
According to you guys, it should be Collection< E > as returntype. However, when I try it out, the compiler is ok with my version. No warnings or anything. It runs without error too.

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.97 :

Post by admin »

Hello,
The code that you've pasted here is not exactly same as the code given in the question. The variable type of returnValue in your code is ArrayList<E> (which is why your code compiles), but the in the given code it is is Collection< E>. Return type of ArrayList for the method will not compile once you change your variable type as per the given code.

HTH,
Paul.

Guest

Re: About Question com.enthuware.ets.scjp.v6.2.97 :

Post by Guest »

Right, missed that one!

Razvan

Re: About Question com.enthuware.ets.scjp.v6.2.97 :

Post by Razvan »

This vesion of the code also seems to compile and run without errors:

import java.util.*;
public class TestClass
{
public < E extends CharSequence > Collection < CharSequence >
getWordsStartingWith( Collection< E > input , char ch )
{
Collection< CharSequence > returnValue = new ArrayList< CharSequence >();
int len = input.size();
for(E e : input)
{
if(e.charAt(0) == ch) returnValue.add(e);
}
return returnValue;
}

public void checkIt()
{
List<String> a = new ArrayList<String>(); a.add("apple"); a.add("cherry");
Set<StringBuffer> b = new HashSet<StringBuffer>(); b.add( new StringBuffer("pineapple"));
Collection<CharSequence> ac = getWordsStartingWith(a, 'a');
Collection<CharSequence> bc = getWordsStartingWith(b, 'b');
}

public static void main(String[] args)
{
new TestClass().checkIt();
}
}

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests