Problem mit Generics

Status
Nicht offen für weitere Antworten.
Hallo,

ich habe hier ein kleines Problem mit Generics und hoffe dabei auf eure Hilfe.
Java:
public interface IKeyFactory<K,V> {

	/**
	 * Creates a key for the given object.
	 */
	public K createKey(V object);
	
}


/**
 * Default implementation for IKeyFactory.
 */
public class KeyFactoryDefImpl<V> implements IKeyFactory<V, V> {
	
	/**
	 * The key for the given object is the object itself.
	 */
	public V createKey(V object) {
		return object;
	}

}


import java.util.HashMap;
import java.util.Map;

public class ListMap<K,V> {

	private IKeyFactory<K,V> keyFactory;
	private Map<K,V> map;
	
	public ListMap(IKeyFactory<K,V> keyFactory) {
		this.keyFactory = keyFactory;
		this.map = new HashMap<K,V>();
	}
	
	public ListMap() {
		this(new KeyFactoryDefImpl<V>());
	}
	
	public void addElement(V element) {
		K key = keyFactory.createKey(element);
		map.put(key, element);
	}
}

Der leere Konstruktor von ListMap ist nicht erlaubt, da dann in ListMap K==V sein müsste. Ist ListMap aber mit K!=V initialisiert würde ich bei addElement eine ClassKastException bekommen da der Key ja vom Typ V und nicht vom Typ K ist. Wie kann ich garantieren, dass in diesem Fall ListMap mit K==V initialisiert wurde?
 
ich glaube, da gibt es keine Möglichkeit, also den Konstruktor entfernen,

reicht stattdessen folgende statische Factory-Methode?
Java:
	public static <V> ListMap<V, V> createMap() {
		return new ListMap<V, V>(new KeyFactoryDefImpl<V>());
	}
 
Vielen Dank übrigens für die Lösung:

Java:
import java.util.HashMap;
import java.util.Map;

public class ListMap<K,V> {

	private IKeyFactory<K,V> keyFactory;
	private Map<K,V> map;
	
	private ListMap(IKeyFactory<K,V> keyFactory) {
		this.keyFactory = keyFactory;
		this.map = new HashMap<K,V>();
	}
	
	public static <V> ListMap<V,V> create() {
		return new ListMap<V,V>(new KeyFactoryDefImpl<V>());
	}
	
	public static <K,V> ListMap<K,V> create(IKeyFactory<K,V> keyFactory) {
		return new ListMap<K,V>(keyFactory);
	}
	
	public void addElement(V element) {
		K key = keyFactory.createKey(element);
		map.put(key, element);
	}
}
 
Status
Nicht offen für weitere Antworten.

Zurück
Oben