0

I know that we use comparable function for sorting ArrayList of objects to sort according to a certain property of objects. But i always wonder when we call sort directly on ArrayList of objects for example: Collections.sort(arraylist); It gives error that you cant sort but actually when you print a object for example:

Instances in1=new Instances();
ArrayList  al=new ArrayList();
al.add(in1);
System.out.println(al.get(0));

You get output:

Instances@45a8123b

which is the id of a object.

So, if we call sorting on an ArrayList then it can sort objects according to id. So, why we get errors while sorting ArrayList of objects ?

4
  • Why would you want to sort objects based on hashCode? Commented Apr 25, 2015 at 0:16
  • sorting based on this id, actually it is hashcode, does not make any sense, why would people implement it? Commented Apr 25, 2015 at 0:16
  • @Lashane u are right i was just asking that by default u can have that option.For example if u want tp print student name according to the date of entry then u can print object. Its a vague example but something like this. Commented Apr 25, 2015 at 0:32
  • @ArjunChaudhary With Java 8 you can do things like that really easily. E.g. students.sort(Comparator.comparing(Student::getDate));. Commented Apr 25, 2015 at 0:37

1 Answer 1

3

If you want your objects to be sortable without supplying a comparator, define a natural ordering by implementing Comparable interface:

class Instances implements Comparable<Instances> {

    ....

    @Override
    public int compareTo(Instances other) {
        return Integer.compare(
                System.identityHashCode(this), 
                System.identityHashCode(other)
        );
    }
}

And now ArrayList<Instances> can be sorted by identity hashcode (however ridiculous it is to actually do that).

This way you actually have to make a deliberate effort for this to happen. Collections.sort is right to not assume a behavior that's likely wrong. If you didn't implement Comparable and didn't supply a Comparator, it is much better to error out than to just silently sort your list in semi-random order.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.