This is my code of finding common elements from three arrays. I am trying to add the elements in the ArrayList by using add() function but I am getting this out of memory error. This is my code-
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList<Integer> ls=new ArrayList<Integer>(n1);
int i=0,j=0,k=0;
while(i<n1 && j<n2 && k<n3){
if(A[i]==B[j] && B[j]==C[k]){
int t=A[i];
ls.add(t);
}else if(A[i]<B[j]){
i ;
}else if(B[j]<C[k]){
j ;
}else{
k ;
}
}
return ls;
}
this is my error-
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Arrays.copyOf(Arrays.java:3720)
at java.base/java.util.Arrays.copyOf(Arrays.java:3689)
at java.base/java.util.ArrayList.grow(ArrayList.java:237)
at java.base/java.util.ArrayList.grow(ArrayList.java:242)
at java.base/java.util.ArrayList.add(ArrayList.java:485)
at java.base/java.util.ArrayList.add(ArrayList.java:498)
at Solution.commonElements(GFG.java:68)
at GFG.main(GFG.java:36)
CodePudding user response:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Java is saying it ran out of memory. There is an endless loop that causes the condition to never exit while loop, endlessly incrementing one of the variables until memory cap has been reached. Review the conditions of while flow control.
CodePudding user response:
When the common elements are being found i.e
if(A[i]==B[j] && B[j]==C[k]){ int t=A[i]; ls.add(t); }
You haven't incremented either i or j or k, hence it is getting stuck in an infinite loop leading to the heap space usage. Incrementing them should do the job ideally.
CodePudding user response:
I needed to increment of i,j,k in my if condition to prevent it from this error.
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList<Integer> ls=new ArrayList<Integer>(n1);
int i=0,j=0,k=0;
while(i<n1 && j<n2 && k<n3){
if(A[i]==B[j] && B[j]==C[k]){
if(!ls.contains(A[i])){
ls.add(A[i]);
}
i ;
j ;
k ;
}else if(A[i]<B[j]){
i ;
}else if(B[j]<C[k]){
j ;
}else{
k ;
}
}
return ls;
}