简体   繁体   中英

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM