Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

A generics working example: how to embed two classes

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


I'd like to introduce you a very important forward leap towards a stronger typization in the Java 5 language: generics.

This is a full working example.

Contents

the article

The following class Pair has 2 type parameters, E and F, and its instances are pair of objects where we have defined the obvious projections. Look out the type variables in the body of the class.

This class could be useful in the quite common situation where a method has to return 2 values.

Be careful that the filename .java and the constructor of the generic class are just Pair and NOT Pair<E,F>.

Note also that when you declare more than one formal parameter these are bounded between a single couple of angular parenthesis and separated by commas.

Pair.java

public class Pair<E,F> {
    // internal rappresentation
    private E first;
    private F second;
 
    // constructor
    public Pair(E first, F second){
	this.first = first;
	this.second = second;
    }
 
    public E getFirst() {
      return first;
    }
 
    public F getSecond() {
      return second;
    }
 
    // toString - overridden from Object
    public String toString(){
	return "("+ first + "," + second + ")";
    }
}


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.