-3

重複の可能性:
Java: 任意の数のパラメーターをサポートする関数を作成するにはどうすればよいですか?

入力パラメーターに関係なく、他の関数からジェネリック関数を呼び出す方法はありますか? 入力データ型がすべて同じ場合 (int のみまたは String のみ)

public class sumOfNo {

public static void main(String[] arg) {

    /**
     * Normal way of calling function to calculate sum.
     */
     int result = sum(1, 2);
     int result1 = sum(1, 2, 3);

}

/**
 * A normal function overloading method of calculating sum
 * @return
 */

 private static int sum(int i, int i0) {
     int c = i + i0;
     System.out.println("c:" + c);
     return c;
 }

 private static int sum(int i, int i0, int i1) {
     int c = i + i0 + i1;
     System.out.println("c:" + c);
     return c;
 }

}
4

4 に答える 4

4

このように来てみてください

public int sum(int... args) {  
  int sum = 0;  
  for (int i : args)  
    sum += i;  
  return sum;  
}

その後、あなたは呼び出すことができます

sum(3);
sum(3, 4, 5);
sum(3, 4, 5, 6, 7);

erit: amit は 5 秒速くなりました :)

于 2013-01-17T08:41:58.237 に答える
1

これを試して :

public class Main
{
    public static void main(String[] argv)
    {
        int result1 = sum(1, 2);
        int result2 = sum(1, 2, 3);
        int result3 = sum(1, 2, 4, 5, 6, 1000);

        System.out.println(result1 + "\n" + result2 + "\n" + result3);
    }

    private static int sum(int... args)
    {
        int ret = 0;

        if (args != null)
        {
            for (int val : args)
            {
                ret += val;
            }
        }
        return ret;
    }
}
于 2013-01-17T08:55:22.693 に答える
0

クイックアプローチ

これは解決策になる可能性があります (注:常に意味のある変数名を使用してください!):

private static int sum(int i, int... others) {
    int sum = i;

    if(others!=null)
        for(int other : others) {
            sum+=other;
        }
    }
    System.out.println("sum:" + sum);
    return sum;
}

引数に注意してください。1 つの数値を合計することはあまり意味がないため、この構成により、少なくとも 1 つの int が入ってくることが保証されます。また、これは vararg の null 値もチェックします。

溢れる感情…

これを実行すると、クイックアプローチで何が起こるでしょうか:

int veryBigNumber = sum(Integer.MAX_VALUE, 1);

veryBigNumber実際には==Integer.MIN_VALUE...

これは問題になる可能性があります。オーバーフローが発生しても Java は例外をスローしないため、誤った結果になる可能性があります。オーバーフローのチェックを行うことができます:

private static int aLittleBitSaferSum(int i, int... others) throws ArithmeticException {
    int sum = i;
    if(others!=null)
        for(int other : others) {
            if(Integer.MAX_VALUE-other<sum) {
                throw new ArithmeticException("Sum would be too large to fit in int");
            }         
            if(Integer.MIN_VALUE+other>sum) {
                throw new ArithmeticException("Sum would be too small to fit in int");
            }         
            sum+=other;
        }
    }
    System.out.println("sum: " + sum);
    return sum;
}

もちろん、これはただのばかげたチェックです...結果はint、たとえば次のように に非常にうまく収まる可能性があります。

sum(Integer.MAX_VALUE, 1, -1);

どちらが結果になるはずですかInteger.MAX_VALUE-チェックなしです。

視野を広げる

恐れるな!前述の問題も解決できます。たとえば、部分的な結果が常にint範囲内に収まるようにオペランドを順序付けする巧妙なアルゴリズムを提供することによって、それは解決するのが簡単ではない問題だと思います...そして計算能力に多くの費用がかかります.

ただし、関数が処理する値の範囲を拡張することで、はるかに優れた処理を実行できます。

private static int aLittleBitSaferSum(int i, int... others) throws ArithmeticException {
    long sum = i;
    if(others!=null)
        for(int other : others) {
            if(Long.MAX_VALUE-other<sum) {
                throw new ArithmeticException("Sum would be too large for this algorithm to deal with");
            }         
            if(Long.MIN_VALUE+other>sum) {
                throw new ArithmeticException("Sum would be too small for this algorithm to deal with");
            }         
            sum+=other;
        }
    }

    if(Integer.MAX_VALUE<sum) {
        throw new ArithmeticException("Sum would be too large to fit in int");
    }         
    if(Integer.MIN_VALUE>sum) {
        throw new ArithmeticException("Sum would be too small to fit in int");
    }       

    System.out.println("sum: " + sum);
    return (int)sum;
}

これにはまだ制限がlongありますlongが、整数の 2 倍のサイズであるため、問題が発生する可能性ははるかに低くなります。ただし、これは余分な作業が必要なため少し遅くなり、チェックのために読みにくくなります。

全部欲しい

…今すぐ欲しい。範囲はまだ問題になる可能性がありますが、これは解決策です:

private static int aSafeButSlowerSum(int i, int... others) throws ArithmeticException {
    BigInteger sum = BigInteger.valueOf(i);
    BigInteger intMax = BigInteger.valueOf(Integer.MAX_VALUE); //should be a private static final class variable
    BigInteger intMin = BigInteger.valueOf(Integer.MIN_VALUE); //should be a private static final class variable

    if(others!=null)
        for(int other : others) {
            sum=sum.add(BigInteger.valueOf(i));
        }
    }

    if(intMax.compareTo(sum)<0) {
        throw new ArithmeticException("Sum would be too large to fit in int");
    }         
    if(intMin.compareTo(sum)>0) {
        throw new ArithmeticException("Sum would be too small to fit in int");
    }       

    System.out.println("sum: " + sum.toString());
    return sum.intValue;
}

これはすべての BigInteger が原因でさらに遅くなりますが、上記の関数の問題は見られません。(したがって、他のオプションと同様に「現在」は少し少なくなりますが、追加料金を支払う必要があります..)

于 2013-01-17T09:12:17.177 に答える
-1
public static void main(String[] arg) {
    int result2 = sumVarArgs(1, 2);
    System.out.println(result2);
    int result3 = sumVarArgs(1, 2, 3);
    System.out.println(result3);
    int result4 = sumVarArgs(1, 2, 3, 4);
    System.out.println(result4);
    int result5 = sumVarArgs(1, 2, 3, 4, 5);
    System.out.println(result5);

}


    /**
     * Aoccepts an all int variables and conciders them as an array and adds
     * them
     *
     * @param argsAry multiple number of input parameters having data type
     * <i>int</i>
     * @return sum of all passed int variables in int format
     */
public static int sumVarArgs(int... argsAry) {
     int c = 0;
     for (int i = 0; i < argsAry.length; i++) {
         c += argsAry[i];
     }
     return c;
}
于 2013-01-17T08:39:23.497 に答える