I have two arrayLists and I am trying to "subtract" one arrayList from another. For example, if I have one arrayList [1,2,3] and I am trying to subtract [0, 2, 4] the resulting arrayList should be [1,3].
List<Integer> a = new ArrayList<>(Arrays.asList(1, 2, 3)); List<Integer> b = Arrays.asList(0, 2, 4); subtract(a,b) // should return [1,3]
Here is my code.
//returns a new IntSet after subtracting a from b // .minus().toString() ArrayList<Integer> minusArray = new ArrayList<Integer>(); minusArray.addAll(array1); for(int i =0; i< minusArray.size(); i++){ for(int j = 0; j < array2.size(); j++){ if(minusArray.get(i).equals(array2.get(j))){ minusArray.remove(i); if(i == 0){ ; } else if(j == 0){ ; } else{ i = 0; j = 0; } } else{} } } return minusArray;
My code works in some cases, like if arrayList1 = [4,6]
and arrayList2 = [6]
it will will give me a result of [4]
. But if I try something like [1,2,4]
and [0,4,8]
I get this exception:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2 at java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at IntSet.minus(IntSet.java:119) at IntSetDriver.main(IntSetDriver.java:62)
Here is the code I have come up with. I have done test runs through it and to me I think it should work. The user inputs these arrayLists and they are presorted, I also do not know Hash or big-O.
ArrayList<Integer> minusArray = new ArrayList<Integer>(); minusArray.addAll(array1); for(int i =0; i< minusArray.size(); i++){ for(int j = 0; j < array2.size(); j++){ if(minusArray.get(i).equals(array2.get(j))){ minusArray.remove(i); } else{} } } return minusArray;
The clone() method of the ArrayList class is used to clone an ArrayList to another ArrayList in Java as it returns a shallow copy of its caller ArrayList. Syntax: public Object clone();
Is there some reason you can't simply use List.removeAll(List)?
List<Integer> one = new ArrayList<Integer>(); one.add(1); one.add(2); one.add(3); List<Integer> two = new ArrayList<Integer>(); two.add(0); two.add(2); two.add(4); one.removeAll(two); System.out.println(one); result: "[1, 3]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With