views:

19

answers:

2

Dear all,

In Java, we can use variadic function in the following way:

public Set packStrings(String...strings){
    for (String str : strings){
         //Do something on the str
    }

    //How to convert strings into a Set?
}

My question is, what is the type of "strings"? is it String[]? How to put the string(s) denoted by the "strings" into Java Collection, such as Set or List?

Please kindly advise.

Thanks & regards, William Choi

+3  A: 
public Set<String> packStrings(String...strings){

    //Way 1 to create List
    List<String> strList = new ArrayList<String>();
    for (String str : strings){
         //adding to list
         strList.add(str);
    }
    //way 2 to create List
    List<String> strList = Arrays.asList(strings);
    //converting to set from List
    Set<String> setStr= new HashSet<String>(strList);
    return setStr;
}  

Have a look at this Doc

org.life.java
@org.life.java You need to return setStr ;) and specify the generic in the method definition.
Carlos Tasada
@Carlos Tasada Oh..yes.
org.life.java
Great! got it, thanks.
William Choi
A: 

It's a string array, so you can do:

Arrays.asList(strings);
Ben Taitelbaum
Thanks Ben, so "strings" isa String[], right?
William Choi
@William Choi Yes. http://download.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
org.life.java