'Is it possible to make a function return a generic collection of generic type

The input to a function are the following

  1. File path
  2. Collection class
  3. Element class
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

  1. collectionClass = HashSet and elementClass = Integer -> Function should return HashSet<Integer>
  2. collectionClass = ArrayList and elementClass = String -> Function should return ArrayList<String>


Solution 1:[1]

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");
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konrad Höffner