0

Below is my code where I want to compare two array elements and add corresponding elements to a new array(foundArray) and not found elements to other array(notFoundArray).

public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i <= originalArray.length; i++) {
        for (int j = 0; j <= keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
            } else if (originalArray[i] != keyArray[j]) {
                System.out.println("Not Found");
                notFoundArray.add(originalArray[i]);
            }
        }
    }
}

This isn't working.It's giving me ArrayIndexOutOfBoundsException and also executing only else statement.I have googled for it but no correct answer.

Any help is appreciated.Thank you!

6
  • 1
    your logic seems flawed. don't decide whether it's found or not, until you've checked them against every element of keyArray. now you add them (and decide) after every single element of keyArray is checked Commented Sep 5, 2018 at 9:47
  • Use < array.length instead <= array.length to get rid of the ArrayIndexOutOfBoundsException. Commented Sep 5, 2018 at 9:48
  • as for your indexOutOfBounds: change this: <= to this: < .otherwise you'll try to get the Xth element of an array which only has X-1 elements Commented Sep 5, 2018 at 9:49
  • simply way follow this approach stackoverflow.com/questions/8103621/… Commented Sep 5, 2018 at 9:51
  • Further reading: How to properly compare two Integers in Java? Commented Sep 5, 2018 at 9:53

7 Answers 7

2

Last index of ann array is length-1 because the first index is zero so your code must be

for (int i = 0; i < originalArray.length; i++) {
    for (int j = 0; j < keyArray.length; j++) {
Sign up to request clarification or add additional context in comments.

2 Comments

it is working fine for found elements but for not found elements it is printing the elements for all the loop iterations
Because you compare in each Iteration against all values from secon array
2

I suppose that you want to compare input array to array of key, and order is not important.

public static void main(String[] args) {

        Set<Integer> originalArray = Arrays.asList(12, 54, 19, 20, 44, 32, 14, 63, 57, 28).stream().collect(Collectors.toSet());
        Set<Integer> keyArray = Arrays.asList(20, 44, 50, 62, 23, 28, 19, 57, 60, 99).stream().collect(Collectors.toSet());

        List<Integer> foundArray = new ArrayList<>();
        List<Integer> notFoundArray = new ArrayList<>();

        for (Integer i : originalArray) {
            if (keyArray.contains(i)) {
                foundArray.add(i);
            } else {
                notFoundArray.add(i);
            }
        }

        System.out.println("Found");
        foundArray.forEach(System.out::println);
        System.out.println("Not found");
        notFoundArray.forEach(System.out::println);
    }

Comments

1

I see two problems with your code. First, your loop bounds are incorrect, because an array of size N can only be addressed up to N-1. Second, and perhaps more important, you should do the bookkeeping for each original number after the inner scan loop over the lookup values, not inside it. Taking both of these into account:

for (int i=0; i < originalArray.length; i++) {
    boolean found = false;
    for (int j=0; j < keyArray.length; j++) {
        if (originalArray[i] == keyArray[j]) {
            System.out.println("Found");
            found = true;
            break;
        }
    }

    if (found) {
        foundArray.add(originalArray[i]);
    }
    else {
        notFoundArray.add(originalArray[i]);
    }
}

In your current approach, you would be adding the same initial number multiple times to the two collections. Most likely, you don't want this behavior.

Comments

1

There are multiple problems (<= instead of < and the logic). This should work:

public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i < originalArray.length; i++) {
        boolean found = false;

        for (int j = 0; j < keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
                found = true;
                break;
            }
        }

        if(found == false) {
            System.out.println("Not Found");
            notFoundArray.add(originalArray[i]);
        }
    }
}

Comments

1
 public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i < originalArray.length; i++) {
        for (int j = 0; j < keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
            }
        }
    }
}

This won't throw an ArrayOfOfBoundsException and will give you all found elements. To get the unfound elements just take one array and compare it with the ' foundArray '.

Comments

1

If you are interessted in a Stream version which just produces the two final lists of integers this code will do it:

    Set<Integer> keys = new HashSet<>(Arrays.asList(keyArray));

    Map<Boolean, List<Integer>> partionedIntegers = Arrays.stream(originalArray).collect(Collectors.partitioningBy(keys::contains));
    List<Integer> foundArray = partionedIntegers.get(true);
    List<Integer> notFoundArray = partionedIntegers.get(false);

Please note that this will return two List<Integer> with distinct Integer while the code in the question will result in two lists containing duplicates.

More over this code will work with different array lengths.

And referring to my comment on the question:
HashSet.contains will use hashCode and equals, not the object identity (==) to determine equality.

Comments

1

This is also another version using Streams.

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<>();
    List<Integer> notFoundArray = new ArrayList<>();

    Stream.of(keyArray).forEach(p -> {
            boolean result = Stream.of(originalArray).anyMatch(s -> s.intValue()==p.intValue());
            if(result) {
                foundArray.add(p);
            }else {
                notFoundArray.add(p);
            }
    });

Comments

Your Answer

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.