I need a java method to convert Generic List of objects to Chunk.
e.g. from List<CustomObject>
to Chunk<CustomObject>
The changes i have done below :
Change-1: (Working)
public static Chunk<CustomObject> convertListToChunk(List<CustomObject> listObject) {
Chunk<CustomObject> chunkObject = new Chunk<>(listObject);
return chunkObject;
}
Change-2: (Not working)
public static Chunk<? extends Object> convertListToChunk(List<? extends Object> listObject) {
Chunk<? extends Chunkable > chunkObject = new Chunk<>(listObject);
return chunkObject;
}
In this case we can also use BaseCustomObject
like Chunk<? extends BaseCustomObject>
where BaseCustomObject
is super class of all custom object
Calling converter Method
List<CustomObjectX> finalList = new ArrayList<>();
Chunk<CustomObjectX> chk = convertListToChunk(finalList)
here CustomObjectX is any type custom object, or extends BaseCustomObject
Chunk<?>
is short for Chunk<? extends Object>
- hence, writing that out is meaningless.
You're looking for:
public static <W> Chunk<W> convertListToChunk(List<W> list) {
return new Chunk<W>(list);
}
Which seems useless. This method already exists. It's... new Chunk<>(list);
.
Generics serves to link things. Here, you want to link the the list's component type to the chunk's type. Declare a variable (<W>
declares it), then use it in at least 2 places (because generic variables used only once are either useless, or some hackery; either way not a good idea generally).