Java – deletes items from the index when looping through the list
public boolean isTwoPair() {
public boolean isTwoPair() { boolean isTwoPair = false; Collections.sort(deck); List<Card> cards = new LinkedList<Card>(deck); System.out.println(cards); for (int i = 0; i < cards.size()-1; i++) { for (int j = i + 1; j < cards.size()-1; j++) { if (deck.get(i).equals(deck.get(j))) { cards.remove(i); cards.remove(j); System.out.println(cards); } } } return isTwoPair; }
I think my problem is my cards Remove() When I delete a card, the next time the card is deleted, it will delete it from the changed list Is there any way to delete two items with the same index number from the list?
If I have to delete index 0,1, because they are all like this:
[Ace,Ace,Three,Four,Four]
Code to delete it (delete index 0)
[Ace,Four]
Instead of removing index 1 (ACE) from the first list, it is removed from the second list
[Ace,Four]
It removes index 1 from the second list, which is three
That's what I expect
[Three,Four]
At this point, I want my loop to pick and delete four and four
Edit:
public boolean isTwoPair() { boolean isTwoPair = false; Collections.sort(deck); List<Card> cards = new LinkedList<Card>(deck); System.out.println(cards); for (int cardOne = 0; cardOne < cards.size(); cardOne++) { for (int cardTwo = cardOne + 1; cardTwo < cards.size(); cardTwo++) { if (deck.get(cardOne).equals(deck.get(cardTwo))) { cards.remove(cardOne); cards.remove(cardTwo-1); System.out.println(cards); for(int cardThree = 0; cardThree < cards.size(); cardThree++){ for(int cardFour = cardThree+1; cardFour < cards.size(); cardFour++){ if(cards.get(cardThree).equals(cards.get(cardFour))){ cards.remove(cardThree); cards.remove(cardFour-1); System.out.println(cards); isTwoPair = true; } } } } } } return isTwoPair; }
This is what I am using now. If I don't have to do this, I really don't want to create a new variable, so I decided not to delete object
Solution
If you know that j is always greater than I (because of the for loop), if you delete the element with index I first, you can delete the element with index J – 1 to get the expected result
cards.remove(i); cards.remove(j-1);