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
Integer
andLong
are compared by reference, not by value. If you're familiar with Python, it's likea is b
nota == b
, or, if you know C++, it's&a == &b
nota == b
.Java, like many other languages like Python, has small integer optimization, meaning that it prebuilds all
Integer
s andLong
s from -128 to 127. When you convertlong
toLong
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 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 returnfalse
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)
, 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
get
ofArrayList
actually returns aLong
object, not along
primitive. Comparing 2Long
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 theequals
orcompareTo
method of theLong
object, likeif (!a.get(i).equals(a.get(i - 1))
, or even the static methodcompare
.Your second code using the
-
operator, which actually unboxLong
objects tolong
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.
Sure ..I'll keep that in mind..Thanks