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

Recommended Answers

All 5 Replies

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.

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.

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

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

Thank you James...:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.