-3

I'm trying to understand, how the compareTo method is called in this program.

class Student implements Comparable {
    String dept, name;

    public Student(String dept, String name) {
        this.dept = dept;
        this.name = name;
    }

    public String getDepartment() {
        return dept;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        return "[dept=" + dept + ",name=" + name + "]";
    }

    public int compareTo(Object obj) {
        Student emp = (Student) obj;
        System.out.println("Compare to : " +dept.compareTo(emp.getDepartment()));
        int deptComp = dept.compareTo(emp.getDepartment());

        return ((deptComp == 0) ? name.compareTo(emp.getName()) : deptComp);
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof Student)) {
            return false;
        }
        Student emp = (Student) obj;
        boolean ii = dept.equals(emp.getDepartment()) && name.equals(emp.getName());
        System.out.println("Boolean equal :" +ii);
        return ii ; 

    }

    public int hashCode() {
        int i2 = 31 * dept.hashCode() + name.hashCode();
        System.out.println("HashCode :" + i2);
        return i2;

    }
}

public class CompareClass {
    public static void main(String args[]) {
        Student st[] = { new Student("Finance", "A"),
                new Student("Finance", "B"), new Student("Finance", "C"),
                new Student("Engineering", "D"),
                new Student("Engineering", "E"),
                new Student("Engineering", "F"), new Student("Sales", "G"),
                new Student("Sales", "H"), new Student("Support", "I"), };
        Set set = new TreeSet(Arrays.asList(st));
        System.out.println(Arrays.asList(st));
        System.out.println(set);
    }
}
  1. Why is Arrays.asList(st) used?
  2. What is use of equals() and hashcode()?
NarutoUzumaki
  • 91
  • 1
  • 1
  • 11

6 Answers6

2

Why Arrays.asList(st) is used ?

Because the TreeSet constructor TreeSet(Collection c) accepts a Collection and not a String[] , hence you convert the String[] to a List which is a Collection using the method List asList(T... a). Note here , the array is same as varargs in this case.

What is use of equals() and hashcode() ?

Object class provides two methods hashcode() and equals() to represent the identity of an object.

You are using a TreeSet in your code . As per the documentation:

the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

Hence in your case , implementing Comparable and overriding compareTo() is enough .


Suggested Reading:

  1. Overriding equals and hashCode in Java.
  2. Hashset vs Treeset
  3. What is the difference between compare() and compareTo()?
Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

.equals() is used because you are comparing two Objects.

Sean Cox
  • 782
  • 1
  • 5
  • 12
1

I m trying to understand ,how the compareTo method is called in this program.

Because what you use here is a TreeSet, which implements SortedSet, and for which uniqueness is calculated by comparing elements using their natural ordering, and not equality.

Classes implementing Comparable of themselves, or a superclass of themselves, can be compared to one another. For classes which do not, you can supply a Comparator instead.

When you add an element to a SortedSet, the set will first compare it to elements already present in the set, and only add it if no comparison gives 0. See below for a demonstration.

See also Collections.sort().

1.Why Arrays.asList(st) is used ?

because this is Java 1.4 code. In Java 5, you'd use Arrays.asList(s1, s2, etc) (ie, a varargs method).

2.What is use of equals() and hashcode() ?

In this case, none.


Sample program (with generics this time) illustrating the difference between a SortedSet and a HashSet, using BigDecimal:

final BigDecimal one = BigDecimal.ONE;
final BigDecimal oneDotZero = new BigDecimal("1.0");

one.equals(oneDotZero); // false
one.compareTo(oneDotZero); // 0

// HashSet: uses .equals() and .hashCode();

final Set<BigDecimal> hashset = new HashSet<>();
hashset.add(one); hashset.add(oneDotZero);
hashset.size(); // 2

// TreeSet: uses Comparable

final Set<BigDecimal> treeset = new TreeSet<>();
treeset.add(one); treeset.add(oneDotZero);
treeset.size(); // 1
fge
  • 119,121
  • 33
  • 254
  • 329
1

There is a very good explanation of the Comparable interface in the Oracle documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

In this code, Arrays.asList(st) is used basically because the author thought it was simpler to instantiate an Array in Java and convert it to a List than it is to create an ArrayList and call .add for each item. It's really not critical to what is going on, though. Another thing that happens on that same line is where the magic is.

Set set = new TreeSet(Arrays.asList(st));

This creates a TreeSet from the list. It is worth taking a look at this post: What is the difference between Set and List? briefly. In a Set, all elements are unique, so when you create a Set from a List that contains duplicates the Set constructor will throw the extra items away. How does it determine what elements are duplicates? It uses the methods of the Comparable interface. Similarly, a List is sorted but a Set is not so the implementation can choose to store the items in the Set in whatever order is most efficient. In the case of a TreeSet it handily explains how it does it right at the top of the Oracle documentation:

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Community
  • 1
  • 1
seanmk
  • 1,934
  • 15
  • 28
1

Some of the Java API was built around arrays and some of it was built around collections. asList is basically an adapter that lets your array be accessed like a collection.

Some data structures and algorithms operate on what's called the "hash" of a piece of data. This is done largely for performance reasons. In most cases the hash is a single number representing a particular object. You can see how this might be useful for sorting a collection quickly or checking equivalence.

equals exists of course to test if two objects represent the same thing.

DubiousPusher
  • 1,132
  • 2
  • 8
  • 19
0

.equals and .hashcode are methods inherited from the Object class in java by every class. When creating your own class you would usually override these two default implementations because the default Object function generally does not lead to the desired behavior.

They are there for good measure really, but as it is they are not being used.

CBIII
  • 845
  • 1
  • 9
  • 9