1

is it possible to create a class and have a String ... attribute that takes as many or as little strings as you put? example: please excuse my rough pseudocode, this is for java.

//this is the method:
public void getXXXX(String ...) {
//random code executes in a loop with as many as strings that are inputted
}

//this code calls it
getXXXX("Benjamin","Jordan","Steve")
getXXXX("Pengu","No")
getXXXX("hi")
2
  • 2
    Search for java varargs. It’s pretty much exactly your pseudocode, except you give the argument a name and it will be an array. Commented Jul 30, 2020 at 1:31
  • 2
    Any reason you're not using a container like ArrayList? Commented Jul 30, 2020 at 2:26

1 Answer 1

2

Yes, what you entered will more or less work, you just need a parameter name after your type.

class StringDecorator {
    public static String join(final String... strings) {
        final var builder = new StringBuilder();
        for (final var string : strings) {
            builder.append(string);
        }
    
        return builder.toString();
    }
}

Then invoke this somewhere

StringDecorator.join("Hello, ", "World!"); // "Hello, World!"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.