Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in equals & instanceof  RSS feed

 
Li Flyworld
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is my code

Problem 1:In Loop1,I find that "null instanceof class" will compile ok but I don't know why?
Problem 2:In Loop2&Loop3, I find Loop3 that when a1 replace a2,the code will compile error and throws NullPointerException,but Loop2 won't.
I've tried many times,but I can't find a answer to explain it.Please help to solve the problem.Very thanks!
[ edited to preserve formatting using the [code] and [/code] UBB tags and to remove the evil tab character -ds ]
[ January 11, 2004: Message edited by: Dirk Schreckmann ]
 
frank vallee
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Li
I think you misunderstand the equals() method. It is used to evaluate if two Objects are the same, not for assigning a value.
if (a1 instanceof A | a2 instanceof B)
Loop 1 will evaluate to true because (true | false) evaluates to true
if (a1.equals(a2))
Loop 2 will evaluate to false because a1 is not equal to a2
if (a2.equals(a1))
Loop 3 will crash because a2 is null and you cannot invoke a method on a null reference.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!