简体   繁体   中英

List or String Array as method argument

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.

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.

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.

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> .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM