Returning generic Maps

Is there a prettier way of doing the following?

public static <T, E> Map<T, E> loadMap(File file, Map<T, E> map) {
	try {
		FileInputStream fis = new FileInputStream(file);
		ObjectInputStream ois = new ObjectInputStream(fis);
		Object o = ois.readObject();
		if(o instanceof Map) {
			map = (Map<T, E>) o;
			System.out.println(map);
		}

		ois.close();
		fis.close();

		return map;

	} catch(IOException | ClassNotFoundException e) {
		e.printStackTrace();
	}

	return null;
}

At first I didn’t return anything, because I thought that Objects(Map in this case) were passed by reference, so I just assigned the value of whatever was read, to passed Map. However, this didn’t alter the value outside of the function call.

So now I need a Map to get the types it uses and then return a map. :confused:

Map<Foo, Bar> foobar;
foobar = (Map<Foo, Bar>) loadMap(file, foobar);

just isn’t as good looking as plain old loadMap(file, foobar); or foobar = loadMap(file) :frowning: (These two variants is the ones I like the most :stuck_out_tongue: (Looks the most pretty xD))

Cheers! :slight_smile:

You could put things into the provided map. As in you don’t create a new map object just use the map object that is passed in. Otherwise this is pretty much how it needs to be done due to type erasure.

Well, I thought I put the map object into the provided map on line 7, however it only sticks as long as I’m inside the function call, thus I have to return the map.

Line 7 reassigned the local variable ‘map’ to point to a different map object from the one passed in.

map.putAll((Map<T,E>)o);

Would work.

Arh, right. I should’ve thought of map.putAll(). :slight_smile:

Thanks a bunch!