I want to create a helper method which gets Collection
type parameter to return a list. This is what I have now:
public class Helper {
public static <T> T[] CollectionToArray(Collection<T> collection) {
return collection.stream().toArray(Object[]::new); // Error
}
public static <T> T[] ListToArray(List<T> list) {
return list.stream().toArray(Object[]::new); // Error
}
}
public class IamSoNoob {
public void PleaseHelpMe() {
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
String[] arrayFromList = Helper.CollectionToArray(list); // Error
String[] arrayFromSet = Helper.CollectionToArray(set); // Error
String[] array = Helper.ListToArray(list); // Error
}
}
My questions are:
- Is it possible to complete
CollectionToArray(Collection<T>)
?- If so, how?
- Also, is it possible to pass
List
andSet
as a parameter in the first place?
- Is it possible to complete
ListToArray(List<T> list)
?- If so, how?
But here are some restrictions due to my personal taste.
- I don't want to use
@SuppressWarnings
- I really want to keep the part
.stream().toArray(Object[]::new)
(Java 8 part!)
And I have a feeling that I need to fix the part Object[]::new
by using something like: <T extends Object>
or <? extends T>
but I can't really figure out.
Please help me out, and please provide an explanation as well, I am often confused by Generic
and ?
.