4

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");
 }
 }
asked Jun 10, 2014 at 14:28
1
  • portOut[i] == result[i] Commented Jun 10, 2014 at 14:35

4 Answers 4

6

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};
Akash Thakare
23k11 gold badges64 silver badges89 bronze badges
answered Jun 10, 2014 at 14:39
1

Just write two for loops and check whether any given element in one array is in the other. So just:

for (int i=0; i< portOut.length; i++){
 for(int j=0;j<result.length;j++) {
 //rest of code
 }
}
answered Jun 10, 2014 at 14:30
1
 for (int i=0; i< portOut.length; i++)
 {
 for(int j=0;j<result.length;j++) 
 {
 if(portOut[i]==result[j])
 {
 //result[j] is the required value you want. You can put this into other array.
 }
 }
 }
answered Jun 10, 2014 at 14:47
1

Make a function that returns a Boolean value.

for(int i = 0; i < portOut.length; i++)
 for(int j = 0; j < result.length; j++)
 if(portOut[i] == result[j])
 return true;
return false;
answered Jun 12, 2014 at 4:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.