0
import java.util.Date;

class House implements  Cloneable,Comparable
{
    private int id;
    private double area;
    private Date Whenbuilt;
    
    public House(int id,double area)
    {
        this.id=id;
        this.area=area;
        Whenbuilt=new Date();
    }
    
    public String toString()
    {
        return id+" "+area+" "+Whenbuilt;
    }
    
    public int compareTo(Object o)
    {
        if(area>((House)o).area)
                return 1;
        else if(area<((House)o).area)
                return -1;
        return 0;       
    }
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

what is the difference if i put (implements Comparable) and if i dont

Edited by Nick Evan: added code tags

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by NP-complete
0

as far as your code is concerned, no difference at all. Every class implements those two anyway. It depends on what you want to do with Comparable. If you want to make a list of all houses and "sort" them based on the compareTo method then you can perhaps use something like Collections.sort if you explicitly implement Comparable. But in most cases (read simple cases) you don't have to be that explicit.

P.S: Before learning JAVA or any other programming language learn how to use CODE TAGS !!
I couldn't give you a proper answer because i skimmed through your post due to lack of readability.

Edited by NP-complete: n/a

0

a Every class implements those two anyway.

Sorry, but that's wrong. Object, for a start, implements neither.
Although many popular classes implement either or both, there are many important classes that don't.

0

oh yes....what i meant was "simple" (again, the definition is subjective) classes like the one that is posted, implements them. Right??

0

As of Java 1.4.2...

Interface Comparable

All Known Implementing Classes:

BigDecimal, BigInteger, Byte, ByteBuffer, Character, CharBuffer, Charset, CollationKey, Date, Double, DoubleBuffer, File, Float, FloatBuffer, IntBuffer, Integer, Long, LongBuffer, ObjectStreamField, Short, ShortBuffer, String, URI

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.