Current location - Quotes Website - Signature design - What does the statement "public int compareTo(Object b)" mean in Java? The source code is as follows (see question supplement):
What does the statement "public int compareTo(Object b)" mean in Java? The source code is as follows (see question supplement):

The function of this method is to compare the time attributes of the two People objects. If they are equal, it returns 0, otherwise it returns the difference between the time attributes of the current People object and the incoming People object.

Personally, I think this method is not well written. Because the second line casts Object b into People, that is to say, the incoming parameter must be an object of People or a subclass. The current method signature can pass in any object. If a non-People or People subclass object is passed in, a cast exception will occur.

So I think this method should be public int compareTo(People p){...}

According to the Java writing specification, I think the calling method of b.time Not great, a getter method should be added for the time attribute. Replace b.time with b.getTime()

Furthermore, someone said that any type can be passed to Object b. I think this is not quite correct. This is indeed true for object types. Because objects in Java are all subclasses of Object. But for the 8 basic types (int, double, boolean, float, char, byte, long, short), directly assigning Object can only be done in JDK5 and above environments, because JDK5 adds an item called autoboxing. Features that can automatically wrap basic data types into corresponding wrapper classes.