how to create a generic constructor for a generic class in java?

JavaGenerics

Java Problem Overview


I want to create a KeyValue class but in generic manner and this is what I've written:

public class KeyValue<T,E> 
{

	private T key;
	private E value;
	/**
	 * @return the key
	 */
	public T getKey() {
		return key;
	}
	/**
	 * @param key the key to set
	 */
	public void setKey(T key) {
		this.key = key;
	}
	/**
	 * @return the value
	 */
	public E getValue() {
		return value;
	}
	/**
	 * @param value the value to set
	 */
	public void setValue(E value) {
		this.value = value;
	}
	
	public KeyValue <T, E>(T k , E v) // I get compile error here
	{
		setKey(k);
		setValue(v);
	}
}

the error says : "Syntax error on token ">", Identifier expected after this token"

how should I create a generic constructor in java then?

Java Solutions


Solution 1 - Java

You need to remove <T, E> from the constructor's signature: it's already there implicitly.

public KeyValue(T k , E v) // No compile errors here :)
{
    setKey(k);
    setValue(v);
}

Solution 2 - Java

Write constructor exactly the same way you wrote other methods

public KeyValue(T k , E v) 
    {
        setKey(k);
        setValue(v);
    }

Solution 3 - Java

the constructor can be written as

public<T,E> KeyValue(T k,E v){}

but its not necessary also we can writepublic KeyValue(T k,E v)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeyed Vahid HashemiView Question on Stackoverflow
Solution 1 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 2 - Javanarek.gevorgyanView Answer on Stackoverflow
Solution 3 - JavaVyankatesh UttarwarView Answer on Stackoverflow