[Java]How to check if one ArrayList contains objects stores in another

  • Context: Java 
  • Thread starter Thread starter sinhasiha
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 6K views
sinhasiha
Messages
2
Reaction score
0
I have two ArrayLists and I want to check if the items stored in one list is also in the other and if it is, store it in a third ArrayList. My problem is that each object from list two is getting stored in list three.

The lists contain:

List one: 50 items
List two: 15 items

Of the 15 items in list two, 10 of them are in List one and these are the ten that I want to store in List three.

Here is the code I have came up with but something is not right. I didn't see it necessary to show the rest of the code since I know storing the objects in list one and two is working properly.

view plainprint?
Note: Text content in the code blocks is automatically word-wrapped
Java:
for (Items item : listTwo){
listThree.add(listOne.contains(item) ? 1 : 0, item);

}



¸.•°*”˜˜”*°•. ¸.•°*”˜˜”*°•.¸
..¸.•°*”˜˜”*°•Thank you.•°*”˜˜”*°•.¸

————————————————
 
Last edited:
Physics news on Phys.org
You are misunderstanding what the "," operand does. The expression "listOne.contains(item) ? 1 : 0, item" first evaluates "listOne.contains(item) ? 1 : 0" giving either 1 or 0, then throws away that result, then evaluates "item", which is just a reference to "item". So apart from wasting a bit of time checking in the item is in listOne, your code does the same thing as "listThree.add(item)", which of course always adds "item" to listThree.

If you really want to use the "? :" operator, you could write something like
Code:
listOne.contains(item) ? listThree.add(item) : 0;
but most people would just write
Code:
if (listOne.contains(item)) 
   listThree.add(item);
 
AlephZero said:
The expression "listOne.contains(item) ? 1 : 0, item" first evaluates "listOne.contains(item) ? 1 : 0" giving either 1 or 0, then throws away that result, then evaluates "item", which is just a reference to "item".

Java does not have a comma operator like C. Instead, what happens is that the add(int,E) method is invoked, that is, the first argument in the invocation will be either 0 or 1 depending on whether the item from the second list exist in the first list or not. Inserting in position 0 or 1 means the item will be insert first or second respectively in the list. If the first item in the second list is contained in the first list, then add is invoked with index 1 on an empty list which would give an IndexOutOfBounds exception.
 
If the "items" stored in your ArrayLists are objects, you can use .Equals to test for "equality", which really checks the memory address.