开发者

In Java, how to make a method able to accept variadic parameters or Set of parameters without duplicating the code of implementation?

开发者 https://www.devze.com 2023-01-26 04:22 出处:网络
I\'m looking for a way so that I can use the same portion of code to deal with parameter passing through Set or variadic parameters. e.g.

I'm looking for a way so that I can use the same portion of code to deal with parameter passing through Set or variadic parameters. e.g.

public void func(String...strs){
    for (String str : strs){
        //Deal with str
    }
}

According to the spec, the func will also supports:

public void func(Set<String> strs){
    for (String str : strs)
   开发者_运维知识库     //Deal with str
    }
}

}

Both the processing code are identical, how can I merge to a single implementation? Please kindly advise.

Thank you.

Regards, William


There is no efficient solution to the problem you pose. Varadic functions receive an array. No magic wand will wave itself and convert from java.util.Set to array.

Further, the semantics don't match, since Set is unordered and forbids duplicates, and array is ordered and permits dups.

you can define the second function as

public void func(Set<String> strs) {
   func(strs.toArray(new String[strs.size()]);
}

and pay for the allocation.


public void func(String...strs){
    func(new HashSet<String>(Arrays.asList(strs)));
}

public void func(Set strs){
    for (String str : strs)
        //Deal with str
    }
}


The best you can do is implement your Set version like this:

public void func(Set<String> strs) {
    return func(strs.toArray());
}


It's an old thread but I think it's better to do it that way because you don't have to convert a complete collection.

public void func(String...strs){
    for (String str : strs){
        func_impl(str);
    }
}

public void func(Set strs){
    for (String str : strs)
        func_impl(str);
    }
}

public void func_impl(String str){
    //Deal with str
}

Plus: No conversion.

Minus: A lot of call (to func_impl) if the collection is large.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号