Pass reference to ArrayLists to a method
here is the whole program:
public class ListMerge
{
public static void main( String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println ("Input length of arraylist 1:");
int n = input.nextInt();
ArrayList x = new ArrayList();
ArrayList y = new ArrayList();
for (int i = 0; i < n; i++)
{
System.out.println ("Input 开发者_如何学编程x[ " + i +"] :" );
x.add(new Integer(i));
}
System.out.println ("Input length of arraylist 2:");
int m = input.nextInt();
for (int i = 0; i < m; i++)
{
System.out.println ("Input y[ " + i +"] :" );
y.add(new Integer(i));
}
}
list int merge(ArrayList<int> x, ArrayList<int> y)
{
List<Integer> all = new ArrayList<Integer>();
all.addAll(x);
all.addAll(y);
System.out.println(all);
return all;
}
}
also tell me how do i call the function merge?
You would just declare a method like this:
List<YourObjectType> mergeArrays(ArrayList<YourObjectType> array1, ArrayList<YourObjectType> array2) {
List<YourObjectType> mergedArray = new ArrayList<YourObjectType>();
// perform merge
return mergedArray;
}
The method as you have written it is expecting to return an int, try:
public List<Type> mergeLists(List<Type> a, List<Type> b) {
List<Type> all = new ArrayList<Type>();
all.addAll(a);
all.addAll(b);
return all;
}
If you want to merge differently, e.g. if there should be some sort of sorting or avoidance of duplicates, then you need to change the addAlls to whatever you need.
Call the method by doing:
List<Type> mergedList = mergeLists(x, y);
The method signatur could be like this:
public static List<YourType> merge(List<YourType> firstList, List<YourType> secondList);
The returned list will be created in the method body and filled with the content of the source lists.
Your code shouldn't compile (but it might be a copy/paste/convert problem). This signature would be syntactically correct:
List<int> merge(ArrayList<int> x, ArrayList<int> y) { ... }
Can't prove it here but it may be a problem with In- and Outboxing. Try this signature instead:
List<Integer> merge(ArrayList<Integer> x, ArrayList<Integer> y) { ... }
and use this declaration in the main methods body:
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
and finally - you're not calling the merge method at all in your code. I'm missing something like
ArrayList<Integer> result = new ListMerge().merge(x,y);
at the very end of the main method body...
精彩评论