开发者

How to pass a String argument to ArrayList parameter

I am trying to pass a String argument to a ArrayList parameter like so:

Class A {
 public void testA (ArrayList arrayInput) {
      // Implement function
      System.out.println("In testA function");
   }
  String a = "new";
  testA(a);
}

I do this because I want to use the same function 开发者_如何学Goto pass both String values and ArrayList values. Is there a work around?

Thanks, Sony


// Option 1: print in String - preferred
public void testA(ArrayList<String> list) {
    for(String str : list) testA(str);
}

public void testA(String s) {
    System.out.println(s);
}



// Option2: print in List - not so preferred
public void testA(ArrayList<String> list) {
    for(String str : list) System.out.println(str);
}

public void testA(String s) {
    ArrayList<String> list = new ArrayList<String>();
    list.add(s);
    testA(list);
}


If you want to use the same function to pass both types, you must overload function:

    Class A {
     public void testA (ArrayList arrayInput) {
          // Implement function
          System.out.println("In testA function");
       }
     public void testA (String stringInput) {
          // Implement function
          System.out.println("In testA function. For String!");
       }
      String a = "new";
      testA(a);
    }

Or you can write a function with generic:

public void testA<T>(T input){...}


You could write overloaded methods as other answeres suggested.

Alternatively you could simply wrap the String object in a List and pass it to testA as shown below:

public static <A> void testA(List<A> list) {
  // some code that works over list
  System.out.println("In testA method");
}

String a = "new";
testA(Arrays.asList(a));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜