Reputation: 759
I am trying to create a method that should dynamically accept the string values and store it in an array list.Am trying to achieve method overloading here. Please see the below example and help me resolve in this:
public static void main(String[] args){
verifyFilesInFolder("folder1", "file1", "file2", "file3");
verifyFilesInFolder("folder2", "file1", "file2");
}
verifyFilesInFolder(String folder, ArrayList ???)
{
List<String> list = new ArrayList<String>();
int size=list.size();
for(int i=0; i<size;i++){
list.add(i); // is this correct??
}
}
After storing it in the array list, i want to compare this expected list with Actual list captured from the application by sorting.
Hope you got the point am looking for. If not ArrayList, please suggest me a way to achieve this by having only one method but the number of files may change while calling that method.
Upvotes: 0
Views: 3521
Reputation: 10206
You have 2 options:
Overloading
Define mulitple methods with the same names but different numbers of arguments:
public void func(String s1) { ... }
public void func(String s1, String s2) { ... }
public void func(String s1, String s2, String s3) { ... }
Varargs
Define a single method that takes any number of args:
public void func(String ...strings) {
// strings is of type String[]
String s1 = strings[0];
String s2 = strings[1]; // note, be careful with ArrayIndexOutOfBoundsException
// generally use a for-each loop
}
This can be called as:
func("1");
func("1", "2");
func("1", "2", "3");
func(new String[] {"1", "2", "3"});
EDIT:
If you want to add these values to a List, you can do this:
verifyFilesInFolder(String folder, String ...strings) {
List<String> list = Arrays.asList(strings);
for (String s : list) System.out.println(s);
}
Some inputs/outputs:
verifyFilesInFolder("folder", "item1");
-> prints "item1"verifyFilesInFolder("folder", "item1", "item2");
-> prints "item1" and "item2"verifyFilesInFolder("folder");
-> prints nothingverifyFilesInFolder();
-> won't compileUpvotes: 1