ZelelB
ZelelB

Reputation: 2000

Alternative to Varargs

I'm implementing a class and its' constructor have to get some Strings as parameters, but I don't know the number of these Strings. I could here pass a vararg parameter (String), but it is a Homework, and we can't use any type of arrays or other uncommon librarys in our solution. (It should be an ArrayList or something likethat because we are learning now the Collections-Framework) I thought to pass a List as parameter to the constructor, but this list have to be filled before, and it's pretty long.. It should be simple.

So the first solution with varargs (which isn't accepted) should be something like:

public MyClass(String... myStrings) 
{
     for (String string : myStrings)
     {
          myStrings.add(string);
     }
}

So it will be usable like that for example:

MyClass example = new MyClass("String1", "String2", "String3");

or

MyClass example2 = new MyClass("String1", "String2");

The second one (which is a bit complicated, since the list should be "filled" before):

public MyClass(List<String> myStrings) 
{
      myPlayers = myStrings;
}

(ps: myPlayer is an instance-variable that will be then inizialized)

So do you have any idea (like the first one but without

Upvotes: 3

Views: 1838

Answers (2)

Erik Pragt
Erik Pragt

Reputation: 14637

In short, my solution would be:

public MyClass(List<String> myStrings) 
{
      myPlayers = myStrings;
}

And then call it with:

List<String> items = new ArrayList<String>() {{ add("first"); add("second"); add("third"); }};
MyClass myClass = new MyClass(items);

No need for builders, just an anonymous subclass of ArrayList in which you'll call the add method of ArrayList. This way you can easily construct the list, without needing varargs/arrays.

Upvotes: 3

Bobulous
Bobulous

Reputation: 13169

Do some research into the Builder Pattern. There is a good discussion about it in the Stack Overflow question When would you use the Builder Pattern?.

If you create a StringListBuilder class, you can simply have a method signature like this:

MyClass(List<String> stringList) {/* ... */}

and you can call the constructor using your builder class like this:

MyClass example = new MyClass(new StringListBuilder("first string").
        add("second string").add("third string").add("and so on").toList());

This will allow you to build a list of any size (including an empty list) without resorting to varargs or arrays.

Upvotes: 3

Related Questions