Return multiple values from a method

Question: How can I return more than one value from a method in Java?

Answer: Two easy ways exist to return multiple values from a function:

  1. Precondition: Method 1 works only if the return values are all of the same type -- all values must be integers or booleans, and so on.

    If your return values meet the precondition, simply return an array of values.

    If your values are of different types, you could cast them all down to object and return them as an array of object. However, this proves dangerous work and requires your method's caller to possess too much knowledge of how the array is filled in.

  2. No precondition: With method 2, simply create a high-level wrapper object. For example, if you would like to return an int, a float, and a boolean, create the following wrapper:

    public class SimpleWrapper
    {
    public SimpleWrapper(int I, float f, boolean b)
    {
    _anInt = I;
    _aFloat = f;
    _aBoolean = b;
    }
    public int getInt() { return _anInt; }
    public float getFloat() { return _aFloat; }
    public boolean getBoolean() { return _aBoolean; }
    private int _anInt;
    private float _aFloat;
    private boolean _aBoolean;
    }


    Of course, the class and method names should make more sense in your context.

發佈了5 篇原創文章 · 獲贊 4 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章