| Author |
problem with equals????
|
Harvinder Singh
Ranch Hand
Joined: Feb 14, 2003
Posts: 90
|
|
//what will be the output and why??? class Eek { static int nth; public int i; private double j; Eek() { i = nth; j = nth * 3.456; nth++; } public boolean equals(Object other) { return (i == ((Eek)other).i); } public static void main(String[] args) { Eek e1 = new Eek(); Eek e2 = new Eek(); e1.i = 1; if (e1.equals(e2)) System.out.println("YES"); else System.out.println("NO"); } }
|
Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
|
 |
Jim Crawford
Ranch Hand
Joined: Sep 08, 2002
Posts: 127
|
|
Ok... here goes. I'd say the output is YES, but I'm sure you confirmed with a compiler and JRE. I haven't yet. Why: Before e1 initialization the class is loaded and nth is set to 0. On e1 initialization the member i is set to nth (0) and nth is incremented afterwards with i's value remaining 0. On e2 initialization the member i is set to nth (1). You then set i of e1 to 1 and since you overrided 'equals' it will return 1 == 1 (true), and print YES. Was that what you were looking for? Cheers. [ January 14, 2004: Message edited by: Jim Crawford ]
|
<img src="cool.gif" border="0"> <img src="graemlins/beerchug.gif" border="0" alt="[beerchug]" /> <br />SCJP 1.4
|
 |
 |
|
|
subject: problem with equals????
|
|
|