JetBrains Academy: Reification - Kamil-Jankowski/Learning-JAVA GitHub Wiki
Photocopiers:
Remember all these good old photocopiers? Let's try to implement something similar with time-proven Java arrays in a dangerous mix with up to date Java Generics.
Your task is to create Multiplicator that receives Folders with anything that can be copied (i.e. implementing Copy interface) and creates an array of Folders with copies of the original Folder content. The mix of generics and arrays is not desirable, but sometimes we need to work in such a way (e.g. when interacting with legacy code) and it worth to spend the time to learn how to deal with it.
The class hierarchy is illustrated by the code snippet:
interface Copy<T> {
T copy();
}
class Folder<T> {
private T item;
public void put(T item) {
this.item = item;
}
public T get() {
return this.item;
}
}
/**
* Class to work with
*/
class Multiplicator {
/**
* Multiply folders and put copies of original folder argument content in each.
*
* @param folder folder which content should be multiplicated
* @param arraySize size of array to return.
* Each array element should have Folder with copy of the original content inside
* @return array of Folder<T>[] objects
*/
public static <T extends Copy<T>> Folder<T>[] multiply(Folder<T> folder, int arraySize) {
// Method to implement
}
}
Note the following:
- It's ok to create new Folder instances
- Objects inside newly created Folders should be copies of the original
- Original Folder object should be left intact (all array entries are copies of the original object)
/**
* Class to work with
*/
class Multiplicator {
public static <T extends Copy<T>> Folder<T>[] multiply(Folder<T> folder, int arraySize) {
List<Folder<T>> multipliedList = new ArrayList<>();
for (int i = 0; i < arraySize; i++) {
Folder<T> newFolder = new Folder<>();
T document = folder.get().copy();
newFolder.put(document);
multipliedList.add(newFolder);
}
return multipliedList.toArray(new Folder[arraySize]);
}
}
or
/**
* Class to work with
*/
class Multiplicator {
public static <T extends Copy<T>> Folder<T>[] multiply(Folder<T> folder, int arraySize) {
Folder<T>[] multipliedFolders = new Folder[arraySize];
for (int i = 0; i < arraySize; i++) {
Folder<T> newFolder = new Folder<>();
newFolder.put(folder.get().copy());
multipliedFolders[i] = newFolder;
}
return multipliedFolders;
}
}