Sunday, April 14, 2024
HomeSoftware EngineeringCounting Technique VarArgs in Java

Counting Technique VarArgs in Java


The problem

Depend what number of arguments a way known as with.

Examples

args_count(1, 2, 3) -> 3
args_count(1, 2, 3, 10) -> 4

The answer in Java code

Some languages discuss with this because the unfold operator. In Java, that is known as a VarArg, which suggests a Variable Quantity of Arguments.

Merely prepend the argument’s title with three dots (...) after which discuss with it like an array of components.

class Arguments {
  public static int countArgs(Object... args) {
    return args.size;
  }
}

Alternatively, you might additionally use a stream on it:

import java.util.Arrays;

class Arguments {
  public static int countArgs(Object... args) {
    return (int) Arrays.stream(args).rely();
  }
}

Or loop by it utilizing a for loop:

class Arguments {
  public static int countArgs(Object... args) {
    int whole = 0;
    for (int i = 0; i < args.size; ++i) { 
      whole++;
    }
    return whole;
  }
}

Check instances to validate our resolution

VarArgs can maintain a number of variable sorts, as illustrated in a few of our take a look at instances under.

import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.math.BigInteger;

public class SolutionTest {
    @Check
    public void sampleTest() {
        assertEquals(3, Arguments.countArgs(1, 2, 3));
        assertEquals(3, Arguments.countArgs(1, 2, "uhsaf uas"));
        assertEquals(1, Arguments.countArgs(1));
        assertEquals(4, Arguments.countArgs('a', 865, "asfhgajsf", new BigInteger("123456")));
        assertEquals(0, Arguments.countArgs());
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments