简体   繁体   中英

Generic return types for a method in an interface

I have an interface for a node: each node has an ID . However, different types of nodes have IDs that can be either integers or Strings. How can I make my interface accommodate the same thing that just has different types?

public interface Hyperspacable {


public int getDimensioninality();

/*
 * Returns the Hyperspacable's object at this dimension
 */
public double getDimValue(int depth);

public double getLat();
public double getLon();
public String getID();


/*
 * Calculates the distance between two Hyperspacable objects of the same dimension
 */
public double distance(Hyperspacable e) throws DifferentDimensionException;
} 

What if you parse the String to an Integer or the Integer to a String? So all results are the same type? You could parse it later back if you need to use the value again.

String.valueOf(int)
Integer.valueOf(String)

If you really need two distinct ID types, I can think of a couple of possibilities: you can make your interface generic or you can replace the getID() method with two methods getIntegerID() and getStringID() (one of which will return null when the other type applies). For the generic interface approach:

public <T> interface Hyperspacable {
    public T getID();
    . . .
}

For both approaches, the integer-valued ID types will have to return an Integer rather than an int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM