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.
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.
If you like our products and services, please help us by posting your review here.
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();
}
}