在Java中,如何根据方法的情况返回String或double?是否可以?

发布于 2024-09-27 21:03:13 字数 399 浏览 7 评论 0原文

例如,我有一个方法,可以在字符串中查找由指定分隔符分隔的数据,但某些项目可能是名称,而其他项目可能是数字。

如果用户调用我的方法从分隔列表中返回项目编号 X,我希望它在项目 X 是名称时返回一个字符串,或者在项目 X 是数字时返回双精度值。

例如,objectName.get(5); 将获取分隔列表中的第 5 项。

我是否必须为此使用某种类型的重载?

或者基于用户知道第 5 项是什么这一事实,我是否必须执行类似 objectName.getDouble(5);objectName.getString(5); 的操作?

但是如果用户不知道第 5 项是什么怎么办?他只需要一个字符串或一个双精度值,具体取决于它是什么。

For example, I have a method that looks through a string for data separated by a specified deliminator, but some items might be a names, and other items might be numbers.

If a user calls my method to return item number X from the deliminated list, i want it to return a string if item X is a name, or a double if item X is a number.

For example, objectName.get(5); would get the 5th item in the deliminated list.

Would I have to use some type of overloading for this?

Or would I have to instead do something like objectName.getDouble(5); and objectName.getString(5); based on the fact that the user knows what item 5 is?

But what if the user doesn't know what item 5 is? He just needs a String or a Double depending on what it happens to be.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

南薇 2024-10-04 21:03:13

这是执行此操作的一种方法:

public Object get() {
    if (blueMoon) {
        return new Double(42.0);
    } else {
        return "fred";
    }
}

请注意,这将返回一个 Double 包装器而不是 double

不过,我认为这不是一个好主意,因为调用者现在必须测试返回值的类型并进行类型转换以对其执行某些操作。

郑重声明,Java 不允许方法返回 Stringdouble,因为这些类型在 Java 类型系统中没有通用的超类型。

Here's one way to do this:

public Object get() {
    if (blueMoon) {
        return new Double(42.0);
    } else {
        return "fred";
    }
}

Note that this will return a Double wrapper rather than a double.

I don't think this is a good idea though, since the caller now has to test the type of the returned value and do a typecast to do something with it.

For the record, Java does not allow a method to return a String or double because these types do not have a common supertype in the Java type system.

在梵高的星空下 2024-10-04 21:03:13

对于这类事情,我更喜欢使用类似于函数式编程阵营的 Maybe/Option 模式的东西。你最终会得到一个像这样的界面:

public abstract class DoubleOrString 
{
    // Constraint isDouble() xor isString()
    public boolean isDouble();
    public boolean isString();

    //Must throw iff !isString()
    public String getString();

    //Must throw iff !ifDouble()
    public Double getDouble();

    public static DoubleOrString wrap(final double wrapMe)
    {
       return new DoubleOrString()
       {
             public boolean isDouble() {return true;}
             public boolean isString() {return false;}
             public Double getDouble() {return wrapMe;}
             public String getString() {throw new RuntimeException();}
       };
    }

    //same for wrap(String)
}

这给客户端带来了问题,因为总是有一个健全性检查,在适当的时间确实有一个 double 或 String。在您的情况下,我只会创建一个 get() 方法,因此当客户端(认为他们)知道类型是什么时,调用是

objectName.get(5).getString();

在您的 get(int) 方法中,而不是返回 String 或 double, return 语句看起来像是

DoubleOrString.wrap(theThingToReturn)

预先做了一些额外的工作,但它在过去已经为我带来了好几次回报。

这是你如何使用它来构建一个(警告 - 这还没有接近编译器)

public static DoubleOrString parseADoubleOrString(String input) {
    try {
        return DoubleOrString.wrap(Integer.parseInt(input))
    } catch (NumberFormatException nfe) {
        return DoubleOrString.wrap(input);
    }
}

,这是客户端的样子

  String input = //get the input from the user somehow
  DoubleOrString parsed = parseADoubleOrString(input);
  if (parsed.isDouble())
      aFunctionThatTakesADouble(parsed.getDouble());
  else
      aFunctionThatTakesAString(parsed.getString());

For this sort of thing, I prefer to use something akin to the Maybe/Option pattern from the functional programming camp. You end up with an interface like:

public abstract class DoubleOrString 
{
    // Constraint isDouble() xor isString()
    public boolean isDouble();
    public boolean isString();

    //Must throw iff !isString()
    public String getString();

    //Must throw iff !ifDouble()
    public Double getDouble();

    public static DoubleOrString wrap(final double wrapMe)
    {
       return new DoubleOrString()
       {
             public boolean isDouble() {return true;}
             public boolean isString() {return false;}
             public Double getDouble() {return wrapMe;}
             public String getString() {throw new RuntimeException();}
       };
    }

    //same for wrap(String)
}

This forces the issue for clients, in that there is always a sanity check that there was indeed a double or String at the appropriate time. In your case, I'd make just one get() method, so when the client (thinks they) knows what the type is, the call is

objectName.get(5).getString();

and in your get(int) method, rather than returning a String or a double, the return statement looks like

DoubleOrString.wrap(theThingToReturn)

It's a little extra work up front, but it has paid of for me several times in the past.

Here's how you'd use it to build one (warning - this hasn't been near a compiler)

public static DoubleOrString parseADoubleOrString(String input) {
    try {
        return DoubleOrString.wrap(Integer.parseInt(input))
    } catch (NumberFormatException nfe) {
        return DoubleOrString.wrap(input);
    }
}

and here's what the client looks like

  String input = //get the input from the user somehow
  DoubleOrString parsed = parseADoubleOrString(input);
  if (parsed.isDouble())
      aFunctionThatTakesADouble(parsed.getDouble());
  else
      aFunctionThatTakesAString(parsed.getString());
岁月如刀 2024-10-04 21:03:13

如果您需要这样做,那么您的设计就有问题。由于原始数据源是字符串,因此您必须接受所有返回值都将是字符串,并将其留给客户端检查结果是否可以转换为数字。

如果您想让客户端免于进行检查,您可以为他提供一个最小的 API,如下所示:

public class ValueExtractor {

    public ValueExtractor(String delimitedText) {
        // ...
    }

    /**
     * Determines whether there is a next element
     * to be returned
     */
    public boolean next() {
        // ...
    }

    public String get() {
        // ...
    }

    /**
     * Returns the value as a Double if possible
     * null otherwise.
     */
    public Double getPossibleDouble() {
        // ...
    }
}

If you need to do this then there is problem with your design. Since the original datasource is String you have to accept that all returned values will be string and leave it to the client to check whether the result can be converted to a number.

If you want to save the client from doing the check, you can provide him with a minimal API which may look something like:

public class ValueExtractor {

    public ValueExtractor(String delimitedText) {
        // ...
    }

    /**
     * Determines whether there is a next element
     * to be returned
     */
    public boolean next() {
        // ...
    }

    public String get() {
        // ...
    }

    /**
     * Returns the value as a Double if possible
     * null otherwise.
     */
    public Double getPossibleDouble() {
        // ...
    }
}
萤火眠眠 2024-10-04 21:03:13

Java 语言不会公开方法返回类型的重载。(正如 Thilo 指出的,这是 Java 语言的限制,而不是 JVM/字节码。)

通常这种类型的事情不太适合 Java 类型系统。人们可以想象返回一个 Either 类型(如 Stephen C 所建议的,比 Object 更受限制的返回类型,以及比 DoubleOrString 更通用的类型,如 Stephen C 所指出的) B. Bear),但在 Java 中使用此类构造所需的一般努力通常会导致简单地使用多个方法,例如 getString(...)getDouble(...)< /代码>。

The Java language does not expose an overload on the return type of a method. (As Thilo pointed out, this is a restriction of the Java language and not the JVM/bytecode.)

Generally this type of thing does not fit well into the Java type system. One could imagine returning an Either<String,Double> type (a more restricted return type than Object as suggested by Stephen C and a more general type than DoubleOrString as pointed out by B. Bear), but the general effort required to use such a construct in Java generally results in simply having multiple methods, e.g. getString(...) and getDouble(...).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文