The input to a function are the following
public <E, C extends Collection> C<E> readCollectionFromFile(String filePath,
Class<C> collectionClass, Class<E> elementClass) {
// read from file and return a collection of type C having elements of type E
}
For example if
collectionClass = HashSet
and elementClass = Integer
-> Function should return HashSet<Integer>
collectionClass = ArrayList
and elementClass = String
-> Function should return ArrayList<String>
Yes, this is possible. For example, you can save a generic collection to a file using serialization and then read it back into an object:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Collection;
import java.util.HashSet;;
public class Main
{
public static <E,C extends Collection<E>> Object readCollectionFromFile(String filePath) throws FileNotFoundException, IOException, ClassNotFoundException
{
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath)))
{
return ((C)ois.readObject());
}
}
public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException
{
Main.<Integer,HashSet<Integer>>readCollectionFromFile("example.ser");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.