XDD_____'s blog

By XDD_____, history, 3 years ago, In English

I was solving C in Div2 #698 and I have a query

105802847 and 105802880 are my submission the only difference is the line

if(a.get(i)-a.get(i-1)!=0){f=false;} and if(a.get(i)!=a.get(i-1)){f=false;}respectively

The first one got accepted while the second one fails the last tc of sample test

Please tell me why this is happening

Thanks.

  • Vote: I like it
  • +2
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it +2 Vote: I do not like it

It's Java for you.

In Java, boxed types such as Integer and Long are compared by reference, not by value. If you're familiar with Python, it's like a is b not a == b, or, if you know C++, it's &a == &b not a == b.

Java, like many other languages like Python, has small integer optimization, meaning that it prebuilds all Integers and Longs from -128 to 127. When you convert long to Long or perform calculations, it checks if the integer is from -128 to 127 and if so, uses the prebuilt object. Otherwise, it builts a new object from scratch.

That's what happens when you use a.get(i)-a.get(i-1)==0. If the elements are equal by value, their difference is zero, zero is between -128 and 127 so a static object is used both for a.get(i)-a.get(i-1) and 0, so the references are equal.

When you use a.get(i)==a.get(i-1), it may return false if the values are equal but outside -128..127 range because the elements may have different references.

The solution is to use .equals method, i.e. a.equals(b), not a == b.

»
3 years ago, # |
  Vote: I like it +1 Vote: I do not like it

You should know that ArrayList (and other Collections) only works with Objects. So the method get of ArrayList actually returns a Long object, not a long primitive. Comparing 2 Long objects with == or != only check if they are the same object, not checking whether they are having the same value. To check the values you can either use the equals or compareTo method of the Long object, like if (!a.get(i).equals(a.get(i - 1)), or even the static method compare.

Your second code using the - operator, which actually unbox Long objects to long primitives, therefore the result is correct.

I really recommend you to read the documentation or your tutorial or whatever you are using to learn this language more carefully.