Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value exists in an array in Java?

Tags:

java

arrays

How to check if a value already exists in other array. like in the code below I wanted to check which values of result array are in the portOut array. I am not getting it right. Used Array.asList(result[i]).contains(portOut[i]) but something is wrong...

int[] portOut = {4000,4001,4002,4003,4004,4005,4006,4007,4008,4009};
int[] result = {4001, 4005, 4003, 0, 0, 0, 0, 0, 0, 0}; 

for (int i=0; i< portOut.length; i++){
   if(Arrays.asList(result).contains(portOut[i])){
      System.out.println("out put goes to " + portOut[i] );
   }
   else{
     System.out.println("output of " + portOut[i]+ " will be zero");
      }
   }
like image 609
iAnas Avatar asked Jan 10 '23 10:01

iAnas


1 Answers

Arrays.asList is a generic function that takes a parameter of T... array, in case of int[] the only applicable type is int[], i.e. your list will contain only one element, which is the array if integers. To fix it use boxed primitive types:

Integer[] portOut = {4000,4001,4002,4003,4004,4005,4006,4007,4008,4009};
Integer[] result = {4001, 4005, 4003, 0, 0, 0, 0, 0, 0, 0};
like image 80
cy3er Avatar answered Jan 17 '23 23:01

cy3er