public static void compareJSONArray(JSONArray beforeArr,JSONArray afterArr,List<Long> addIds,List<Long> delIds){ if (CollectionUtils.isEmpty(beforeArr) && CollectionUtils.isEmpty(afterArr)) { return; } the if (CollectionUtils isEmpty (beforeArr) && CollectionUtils. IsNotEmpty (afterArr)) {/ / new addIds = afterArr.stream().map(id -> Long.valueOf(id.toString())).collect(Collectors.toList()); } else if (CollectionUtils isNotEmpty (beforeArr) && CollectionUtils. IsEmpty (afterArr)) {/ / delete delIds = beforeArr.stream().map(id -> Long.valueOf(id.toString())).collect(Collectors.toList()); } else if (CollectionUtils.isNotEmpty(beforeArr) && CollectionUtils.isNotEmpty(afterArr)) { List<Long> allIds = new LinkedList<>(); List<Long> beforeIds = beforeArr.stream().map(id -> Long.valueOf(id.toString())).collect(Collectors.toList()); List<Long> afterIds = afterArr.stream().map(id -> Long.valueOf(id.toString())).collect(Collectors.toList()); allIds.addAll(beforeIds); allIds.addAll(afterIds); allIds = allIds.stream().distinct().collect(Collectors.toList()); For (Long id: allIds) {// Add if (! beforeIds.contains(id) && afterIds.contains(id)) { addIds.add(id); // Delete} else if (beforeids. contains(id) &&! afterIds.contains(id)) { delIds.add(id); } } } } public static void main(String[] args) { JSONArray beforeArr = new JSONArray(); beforeArr.add("1"); beforeArr.add("2"); beforeArr.add("3"); JSONArray afterArr = new JSONArray(); List<Long> addIds = new LinkedList<>(); List<Long> delIds = new LinkedList<>(); compareJSONArrays(beforeArr,afterArr,addIds,delIds); System.out.println(addIds); System.out.println(delIds); }Copy the code

The above code is very simple to determine the difference between two Jsonarrays and store the ID into delIds if it exists in beforeArr but not in afterArr, and addIds if it exists in addIds.

Since I need two return values, addIds and delIds, I pass in the method from outside, and since List is a reference type, I set the value inside the method, which will still be there at the end of the method.

The code in question is shown below

If (CollectionUtils. IsEmpty (beforeArr) && CollectionUtils. IsNotEmpty (afterArr)) {/ / new addIds = afterArr stream (). The map (id - >  Long.valueOf(id.toString())).collect(Collectors.toList()); } else if (CollectionUtils isNotEmpty (beforeArr) && CollectionUtils. IsEmpty (afterArr)) {/ / delete delIds = beforeArr.stream().map(id -> Long.valueOf(id.toString())).collect(Collectors.toList()); }Copy the code

I directly converted the JSONArray into a List and assigned it to addIds and delIds when deciding whether to add or delete.

Important: There is no reference passing in Java, only value passing. Even if you are passing an object, you are passing only a copy of a reference to that object.

While this is something to be aware of when using primitive and string types in methods, it is often overlooked when passing objects, so don’t easily change the object’s reference when passing objects.