import java.util.*;
class Book
{
int id;
String title;
Book(int id, String title)
{
this.id=id;
this.title=title;
}
public String toString()
{
return id+" "+title;
}
}
public class BookDemo
{
public static void main(String args[])
{
List<Book> ar= new ArrayList<Book>();
ar.add(new Book(1,"java"));
ar.add(new Book(2,"C"));
Comparator<Book> com = new Comparator<Book>()
{
public int compare(Book ob1, Book ob2)
{
if(ob1.title.compareTo(ob2.title)>0)
return 1;
else
return -1;
}
};
Collections.sort(ar,com);
for(Book b:ar)
System.out.println(b);
}
}
==========================================================
import java.util.*;
class Book implements Comparable<Book>
{
int id;
String title;
Book(int id, String title)
{
this.id=id;
this.title=title;
}
public String toString()
{
return id+" "+title;
}
public int compareTo(Book ob2)
{
if(this.title.compareTo(ob2.title)>0)
return 1;
else
return -1;
}
}
public class BookDemo
{
public static void main(String args[])
{
List<Book> ar= new ArrayList<Book>();
ar.add(new Book(1,"java"));
ar.add(new Book(2,"C"));
Collections.sort(ar);
for(Book b:ar)
System.out.println(b);
}
}
This comment has been removed by the author.
ReplyDelete