3

I have two arraylists named fw_week and sw_week... Now have to calculate fw_diff which is difference between fw_week and sw_week and sw_diff which is difference between sw_week and fw_week...

I have used like following script,

    fw_diff=fw_week;
    sw_diff=sw_week;
    fw_diff.removeAll(sw_week);
    sw_diff.removeAll(fw_week);

In this, am getting the fw_diff correctly but the fw_week value is also changed which now equal to fw_diff, so the second value sw_diff is giving the wrong value, but i don't want to change the fw_week and sw_week values... So please can anyone help me to solve this issue....

Ramkumar P
  • 209
  • 1
  • 2
  • 14
  • What have you though about the new solution, or you want SO write it for you? – Luiggi Mendoza Jul 19 '12 at 05:14
  • check this questions http://stackoverflow.com/questions/919387/how-can-i-calculate-the-difference-between-two-arraylists http://stackoverflow.com/questions/1235033/java-comparing-two-string-arrays-and-removing-elements-that-exist-in-both-array – Pooya Jul 19 '12 at 05:17

3 Answers3

3
fw_diff= fw_week.clone().removeAll(sw_week)
sw_diff=sw_week.clone().removeAll(fw_week)

More efficient one:

fw_diff= fw_week.clone().removeAll(sw_week)
sw_diff=sw_week.clone().removeAll(fw_diff)

Here,fw_diff contains intersaction of both the list. So now , for sw_diff , we need to remove only fw_diff from sw_week . No need to remove all of fw_week .

Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82
0

You need to clone the arrays:

fw_diff=fw_week.clone();
sw_diff=sw_week.clone();

before you do any removing.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • Thank you Mr.Jon but after finishing calculation i dont want to change the fw_week and sw_week values because i need them further calculation.... – Ramkumar P Jul 19 '12 at 05:20
  • @RamkumarP The `fw_week` and `sw_week` lists are untouched because you're working with clones of them, and not the lists themselves. – Jon Lin Jul 19 '12 at 05:22
  • @RamkumarP You're using Java, right? http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#clone() – Jon Lin Jul 19 '12 at 05:33
0

We do the same thing in our application like this:-

Our scenario is we have 2 arraylist and I need to find the difference between first and second arraylist.

Following is the code snippet:-

this.lstDifference=(ArrayList<String>) ListUtils.subtract(FirstArrayList,SecondArrayList);

The type of arraylist can be changed depending upon your two arraylists.

AngelsandDemons
  • 2,823
  • 13
  • 47
  • 70