Hi,

what does this code exactly do?

implements other class to have the same methods, and then compares two objects of x with y and then returns it to back to the other class??

import java.util.*;

public class TableComparator implements Comparator<customerTable>
{
	
	public int compare(customerTable x, customerTable y)
	{
		return x.compareTo(y);
	}
	
}

Comparator interface:
this is used to sort objects.. let say you are creating a arraylist and you are adding String or Integer in that arraylist, and after that if you are doinf Collections.sort(list); then it will sort this list in natural order.
but assume if you are adding some Employee object in ur arraylist and after that you want to sort it, how will you do that?
here Comparable and Comparator interface comes in a picture.
if you are implementing comparable interface then you need to override compareTo method and if you are implementing Comparator then you need to override compare method.
no in the method you will define that compare employee id or compare employee age or .......
and when you will do Collections.sort(empList); it will sort ur list as per overridden method.

read comparable and Comparator.

if you are implementing Comparable then you need to override compareTo method and sorting sorting will be done like this:
Collections.sort(list);
if you are implementing Comparator then you need to write a class and there you need to override compare method and sorting will be done like this:
Collections.sort(list, obj);
http://www.javapractices.com/topic/TopicAction.do?Id=10

Hi,

what does this code exactly do?

implements other class to have the same methods, and then compares two objects of x with y and then returns it to back to the other class??

import java.util.*;

public class TableComparator implements Comparator<customerTable>
{
	
	public int compare(customerTable x, customerTable y)
	{
		return x.compareTo(y);
	}
	
}
This article has been dead for over six months. Start a new discussion instead.