-3

Here I declare two array lists

ArrayList<Location> possibleMoves = new ArrayList<Location>();
possibleMoves.add(new Location(0, 1));
possibleMoves.add(new Location(1, 0));

ArrayList<Location> possibleMoves1 = new ArrayList<Location>();
possibleMoves1.add(new Location(0, 1));
possibleMoves1.add(new Location(1, 0));

its obvious that those 2 array lists are the same, but when I run this check it always seems to fail.

if(possibleMoves == possibleMoves1){
  System.out.println("lol");
}

I have also tried this and it failed

assertTrue("Player 1 1st piece could play to the left and down!",
arrayListsEqual(possibleMoves, possibleMoves1));

this is the method of arrayListsEqual

private boolean arrayListsEqual(ArrayList<Location> a, ArrayList<Location> b) {
    if (a.size() != b.size()) {
        return false;
    }
    int size = a.size();
    boolean thisOneFound = false;
    for (int i = 0; i < size; i++) {
        thisOneFound = false;
        for (int j = 0; j < size; j++) {
            if (a.get(i).equals(b.get(j))) {
                thisOneFound = true;
                break;
            }
        }
        if (!thisOneFound) {
            return false;
        }
    }
    return true;
}
user3567826
  • 19
  • 1
  • 4

3 Answers3

4

2 issues:

  1. The "Location" objects are different instances. so they are totally unrelated objects.
  2. The list themselves are different instances.

first: you need to check equality with the "equals" method of the lists:

 list1.equals(list2).

also, you need to make sure you save the SAME object in those lists (by using the same instance) or to implement the "equals" and "hashmap" methods in the "Location" class.

once that is done it should work.

good luck :)

APT
  • 365
  • 2
  • 11
  • i understand this but unfortunately i can't modify this assertTrue("Player 1 1st piece could play to the left and down!", arrayListsEqual(possibleMoves, possibleMoves1)); its given in the test file that was created by the professor, so supposedly i should make this work with the assertListsEqual – user3567826 Apr 24 '14 at 08:19
  • 2
    @user3567826 In that case your only requirement is to implement `equals()` and `hashCode` in your `Location` class. – Duncan Jones Apr 24 '14 at 08:31
  • @Duncan you are right!! its stupid of me to miss this! thanks, i guess when you stay awake for 2 days working you miss the small stuff :D – user3567826 Apr 24 '14 at 08:41
0

Please read about the difference between == and equals. == checks whether both References refer to the same instance whereas equals tests for equality. Have a look at the answers to this question.

Community
  • 1
  • 1
Axel
  • 13,939
  • 5
  • 50
  • 79
0

You cannot compare reference objects with == , ArrayList is not a primitive data type.

Immy
  • 57
  • 2
  • 10