-2

I have the below function to check if it is in order

 public boolean order(List<String> value) {
            List<String> tmp = value;
            Collections.sort(tmp);
            return tmp.equals(value);
        }

Test:

assertTrue(route.order(Arrays.asList("a", "s", "d")));
assertFalse(route.order(Arrays.asList("a", "k", "c")));

but fail at 2nd test, why is it not false?

Alvin
  • 8,219
  • 25
  • 96
  • 177
  • 2
    "A", "C", "D" is already ordered, if you order it again, it will still be "A", "C", "D", so why would you expect it to be false? – Matt Jan 11 '19 at 14:16
  • @fantaghirocco no, not a duplicate of that one - in this case here, even the references are equal – Hulk Jan 11 '19 at 14:28

3 Answers3

4

Here in below line:

List<String> tmp = value;

You are just copying reference of value list argument in tmp list and hence you are sorting on tmp and indirectly value list which is one and the same.

To solve the problem change the assignment of tmp variable to:

List<String> tmp = new ArrayList<>(value);
SMA
  • 36,381
  • 8
  • 49
  • 73
2
public boolean order(List<String> value) {
   List<String> tmp = new ArrayList<>(value);
   Collections.sort(tmp);
   return tmp.equals(value);
 }
Sagar P. Ghagare
  • 542
  • 2
  • 12
  • 25
-2

Your asserts are negative to each other. Both arrays are sorted. Maybe you wanted ("A", "C", "B").

Also, as the fellows said before, your sort is on the original list, you have to copy it first and then to sort.

TGH
  • 31
  • 7
  • If you wanted ("A", "C", "B"), then you should not sort the Lists, or maybe use a Comparator other than the NaturalOrder to sort them – DSantiagoBC Jan 11 '19 at 14:23
  • @TGH, you are right. But the real problem is not here, what you point was just a writing mistake in OP question. – vincrichaud Jan 11 '19 at 14:25