Create generic tuple with same class elements
<p>I want to create a generic tuple with two values. For example a tuple with two strings or two integers etc. (Generic values). But it should not be able to mix both elements, for example a string with an integer (Like for example a hash map).</p>

<p>How can I create a type-same tuple? At the moment I use wildcard generics parameter for both elements in the tuple and of course that doesn't force a developer to use the same class type for both elements.</p>

<pre><code>import java.io.Serializable;

public class Main {
    class Element&lt;T extends Comparable&lt;?&gt; &amp; Serializable&gt; {
        private final T element;

        public Element(T element) {
            this.element = element;
        }

        public String raw() {
            return element.toString();
        }
    }

    class Tuple&lt;T extends Element&lt;?&gt;, U extends Element&lt;?&gt;&gt; {
        private final Element&lt;?&gt; element1;
        private final Element&lt;?&gt; element2;

        public Tuple(Element&lt;?&gt; element1, Element&lt;?&gt; element2) {
            this.element1 = element1;
            this.element2 = element2;
        }

        public Element&lt;?&gt; getElement1() {
            return element1;
        }

        public Element&lt;?&gt; getElement2() {
            return element2;
        }
    }

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        Element&lt;String&gt; element1 = new Element&lt;String&gt;(new String("First tuple element"));
        Element&lt;String&gt; element2 = new Element&lt;String&gt;(new String("Second tuple element"));
        Element&lt;Integer&gt; wrongelement = new Element&lt;Integer&gt;(42); // &lt;-- Should not be possible, but it is...
        Tuple&lt;Element&lt;String&gt;, Element&lt;String&gt;&gt; tuple = new Tuple&lt;Element&lt;String&gt;, Element&lt;String&gt;&gt;(element1, element2);

        // First tuple element
        System.out.println(tuple.getElement1().raw());

        // Second tuple element
        System.out.println(tuple.getElement2().raw());
    }
}
</code></pre>