Freedom's blog

By Freedom, history, 7 years ago, In English

Hi.

I've submitted Problem C Round #395 (Div. 2). Why when I change these line

u=nodeColor.get(i);
v=nodeColor.get(a.get(i).get(j));
if (u!=v)

>>Full code

become

if ((Integer)nodeColor.get(i)!=(Integer)nodeColor.get(a.get(i).get(j)))

>>Full code

it get wrong answer?

Thanks!

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

»
7 years ago, # |
Rev. 2   Vote: I like it +18 Vote: I do not like it

You need to compare Integer which is an object using equals rather than using '=' as it is non-primitive so by using '=' you are actually checking whether they refer to same object or not which is not the case as you want to check instead whether they contain the same value or not and that functionality is implemented in it's equals method by overriding equals method of Object class.

  • »
    »
    7 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    looks like string compare

    I always prefer C++ , except bigint, I don't understand WHY java architecture is that...

    • »
      »
      »
      7 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Java doesn't have operator overloading, and its philosophy is "everything is accessed through reference (pointer)". So operator '=' is comparing the addresses of two objects. It's weird.

  • »
    »
    7 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    Thanks, it's accepted when I change

    if ((Integer)nodeColor.get(i)!=(Integer)nodeColor.get(a.get(i).get(j)))
    

    into

    if (Objects.equals(nodeColor.get(i),nodeColor.get(a.get(i).get(j)))==false)
    

    >>Full code