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!

LuCio
  • 5,055
  • 2
  • 18
  • 34
Alekya
  • 239
  • 5
  • 15
  • 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 – Stultuske Sep 05 '18 at 09:47
  • Use `< array.length` instead `<= array.length` to get rid of the `ArrayIndexOutOfBoundsException`. – LuCio Sep 05 '18 at 09: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 – Stultuske Sep 05 '18 at 09:49
  • simply way follow this approach https://stackoverflow.com/questions/8103621/comparing-arrays-that-have-same-elements-in-different-order – sasikumar Sep 05 '18 at 09:51
  • Further reading: [How to properly compare two Integers in Java?](https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java) – LuCio Sep 05 '18 at 09:53
  • ArrayIndexOutOfBounds exception is solved and I change <= to <, it is not comparing the last element – Alekya Sep 05 '18 at 10:08

7 Answers7

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++) {
Jens
  • 67,715
  • 15
  • 98
  • 113
  • it is working fine for found elements but for not found elements it is printing the elements for all the loop iterations – Alekya Sep 05 '18 at 10:01
  • Because you compare in each Iteration against all values from secon array – Jens Sep 05 '18 at 10:03
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);
    }
Bartek
  • 2,109
  • 6
  • 29
  • 40
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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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]);
        }
    }
}
moritz.vieli
  • 1,747
  • 1
  • 14
  • 17
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 '.

Alekya
  • 239
  • 5
  • 15
Mssm
  • 717
  • 11
  • 29
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.

LuCio
  • 5,055
  • 2
  • 18
  • 34
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);
            }
    });
Anoop Kumar
  • 121
  • 1
  • 6