0

Using below piece of code. But it is giving response in object form not in String. Let me know where i m wrong...

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee5 {

    String name;

    public String getName() {
        // TODO Auto-generated method stub
        return name.toString();
    }

    void setName(String nameOfEmp) {
        name = nameOfEmp;
    }

}

class EmpSortByName implements Comparator<Employee5> {
    public int compare(Employee5 o1, Employee5 o2) {
        return o1.getName().compareTo(o2.getName());
    }
}

public class ComparatorExampleInJava {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        Employee5 emp1 = new Employee5();
        emp1.setName("A");
        Employee5 emp2 = new Employee5();
        emp2.setName("C");
        Employee5 emp3 = new Employee5();
        emp3.setName("B");

        List lst = new ArrayList();
        lst.add(emp1);
        lst.add(emp2);
        lst.add(emp3);

        System.out.println("Before Sort : " + lst);

        try {
            Collections.sort(lst, new EmpSortByName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("After Sort  : " + lst);

    }
}

Getting Output: Before Sort : [Employee5@19821f, Employee5@addbf1, Employee5@42e816] After Sort : [Employee5@19821f, Employee5@42e816, Employee5@addbf1]

Desired output: Before Sort : [A, C, B] After Sort : [A, B, C]

Tanu Garg
  • 3,007
  • 4
  • 21
  • 29

4 Answers4

1

You need to implement a method called toString() in Employee5 that returns name.

For example (add to Employee5 )

public String toString() {
    return name;
}

and for further read: How to use the toString method in Java?

Community
  • 1
  • 1
Augusto
  • 28,839
  • 5
  • 58
  • 88
0

It seems, that your should have your own toString() implementtaion within Employee5 class in order to specify how to print them:

class Employee5 {
    ...

    @Override
    public String toString() {
      return name;
    }

}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

When you printing the list, toString() method of your list is called which prints the contents by calling toString() method of the contained objects. You need to override toString() method in your Employee5 class and return the name from it.

Drona
  • 6,886
  • 1
  • 29
  • 35
0
   Iterator itr = lst.iterator();
    while(itr.hasNext()) {
     Employee5 element = (Employee5) itr.next();
     System.out.print(element.getName());
  }  

Hope this Helps.

LMK
  • 2,882
  • 5
  • 28
  • 52