Search code examples
javabooleanargumentsvariadic-functionsargs

Java pass values into method/function


Ok, first of all: hello!

I'll be short.

    public static Boolean or (boolean... args){
    // some code to process args and return true or false
return hasArgs & kiekFalse!=args.length ? true : false;
    } 

Here I have a function called "or" and it has unknown amount of parameters that can be passed into it. I need it, cause I really can't know it. so I can use it like that System.out.println(or(true,true,true,false,true,false)); BUT what to do when I need to read values for example, for keyboard? read and convert to Boolean array? does not work, it requires Boolean, not Boolean[]. Cannot resolve method 'or(java.lang.Boolean[]' Pass one by one? nope, I need to pass none or required amount at once.

Any ideas or suggestions? Ideally, I'd need to figure out how to pass N Booleans from keyboard to or function.. Else I'll just need to rewrite some (a lot of) code.


Solution

  • Create an overload which takes a Collection<Boolean>, converts it to a boolean[], then invokes the method:

    Boolean or(Collection<Boolean> c) {
      boolean[] b = new boolean[c.size()];
      int i = 0;
      for (Boolean cb : c) {
        b[i++] = cb; // assuming no nulls.
      }
      return or(b);
    }
    

    (Or you can take a Boolean[] parameter; it makes little difference, you just have to use length instead of size().)

    Then you can just read your booleans in from user input into a List, and invoke this method.

    List<Boolean> listOfBooleans = new ArrayList<>();
    // Read values, add to list
    Boolean result = or(listOfBooleans);
    

    If you're already using Guava, you can use Booleans.toArray():

    or(Booleans.toArray(listOfBooleans))