Reputation: 96
I am in the luxourious position that I have the freedom to choose whether to implement the following method as an array of Strings:
public void addColumns(String[] columns)
{
for(String column : columns)
{
addColumn(column);
}
}
Or as a Collection of strings:
public void addColumns(List<String> columns)
{
for(String column : columns)
{
addColumn(column);
}
}
What is the best option to implement this? I'm using Java.
Upvotes: 3
Views: 2172
Reputation: 44706
Both a string[]
and a List<string>
allow the method to mutate them.
You only actually need to use an Iterable<string>
to achieve what you do in your example.
I'd use Iterable<string>
because it expresses the minimum that you need (you can iterate over it). This also gives the added benefit that you can pass either a string[]
or a List<string>
into the method.
Using the most restricted type you can communicates intent of what the method will do.
Upvotes: 2
Reputation: 200168
First of all think how you are going to call your method. Do you already have the String array, or you'll have to build it? How do you plan to build it? Choose the solution that will make your client code do less work.
Upvotes: 0
Reputation: 33534
1. I will prefer you to use Collection
when you are working with Java.
2. Java, and the processor have become fast enough that you won't notice any performance difference between an Array or Collection.
3. Collection
gives you a lot of flexibility,and choices to select from List,Set , Maps etc..... whichever suits your need.
4. List<String>
will be the way to go in my opinion.
Upvotes: 3
Reputation: 8401
It entirely depends on the usage.
If you want to keep it light weight then use String[]
.
If you are making insertion deletion sorting and other operations or may use them in future then go for List<String>
.
Upvotes: 2