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.









It's Java for you.
In Java, boxed types such as
IntegerandLongare compared by reference, not by value. If you're familiar with Python, it's likea is bnota == b, or, if you know C++, it's&a == &bnota == b.Java, like many other languages like Python, has small integer optimization, meaning that it prebuilds all
Integers andLongs from -128 to 127. When you convertlongtoLongor 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 fora.get(i)-a.get(i-1)and0, so the references are equal.When you use
a.get(i)==a.get(i-1), it may returnfalseif the values are equal but outside -128..127 range because the elements may have different references.The solution is to use
.equalsmethod, i.e.a.equals(b), nota == b.Oh!! I get it now..Thank you so much
You should know that ArrayList (and other Collections) only works with Objects. So the method
getofArrayListactually returns aLongobject, not alongprimitive. Comparing 2Longobjects 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 theequalsorcompareTomethod of theLongobject, likeif (!a.get(i).equals(a.get(i - 1)), or even the static methodcompare.Your second code using the
-operator, which actually unboxLongobjects tolongprimitives, 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.
Sure ..I'll keep that in mind..Thanks