I am trying some java for first time. I tried creating an arraylist of arraylist and wanted to deep copy one arraylist into another arraylist. When executed the below code I get error:
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
ArrayList<ArrayList<Integer>> arrli = new ArrayList<ArrayList<Integer>>();
System.out.println("Enter the array size: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter "+ n + " elements: ");
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
ArrayList<Integer> arrli1 = new ArrayList<Integer>();
for(int i=0; i<n; i++) {
if(i==0) {
arrli1.add(arr[i]);
} else if(arr[i] > arr[i-1]) {
arrli1.add(arr[i]);
} else if(arr[i] < arr[i-1]) {
arrli.add(arrli1.clone());
arrli1.clear();
arrli1.add(arr[i]);
}
if(i==(n-1)) {
arrli.add(arrli1);
}
}
int s = arrli.size();
int inner_size;
for(int i=0; i<s; i++) {
inner_size = arrli.get(i).size();
for(int j=0; j<inner_size; j++){
System.out.print(arrli.get(i).get(j));
}
System.out.println();
}
}
}
Output:
/MyClass.java:21: error: no suitable method found for add(Object)
arrli.add(arrli1.clone());
^
method Collection.add(ArrayList<Integer>) is not applicable
(argument mismatch; Object cannot be converted to ArrayList<Integer>)
method List.add(ArrayList<Integer>) is not applicable
(argument mismatch; Object cannot be converted to ArrayList<Integer>)
method AbstractCollection.add(ArrayList<Integer>) is not applicable
(argument mismatch; Object cannot be converted to ArrayList<Integer>)
method AbstractList.add(ArrayList<Integer>) is not applicable
(argument mismatch; Object cannot be converted to ArrayList<Integer>)
method ArrayList.add(ArrayList<Integer>) is not applicable
(argument mismatch; Object cannot be converted to ArrayList<Integer>)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
What am I missing here. Please shed some light on this.