简体   繁体   English

接口中方法的通用返回类型

[英]Generic return types for a method in an interface

I have an interface for a node: each node has an ID . 我有一个节点接口:每个节点都有一个ID However, different types of nodes have IDs that can be either integers or Strings. 但是,不同类型的节点具有可以是整数或字符串的ID。 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? 如果将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). 如果你真的需要两种不同的ID类型,我可以考虑几种可能性:你可以使你的接口通用,或者你可以用两个方法getIntegerID()getStringID()替换getID()方法(其中一个将返回null当其他类型适用时)。 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 . 对于这两种方法,整数值ID类型必须返回Integer而不是int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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