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
ListandSetas 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 ?.
Stream.toArray()wouldn't require any parameters.T[]orIntFunction<T>.(T[]) collection.toArray()?Collections.toArray(T[ ])? Why don't you just doString[] arrayFromList =list.toArray(new String[0]);? Whats the reasoning behind writing your own methods when the standard libraries provide tested , trusted and well doing exactly what you want methods?