JAVA 数组中的元素是对象,如何给对象排序
我用数组存储了一些对象(书),每本书都有自己的价格,如何根据书本的价格给书本升序排列呢?比如我在数组中存了三本书,第一本:name:javaEE,price:10第二本:...
我用数组存储了一些对象(书),每本书都有自己的价格,如何根据书本的价格给书本升序排列呢?比如我在数组中存了三本书, 第一本:name:javaEE, price:10 第二本:name:javaSe ,price:5 第三本:name:javaMe ,price:12 如何根据他们的价格升序排列出来呢?
展开
4个回答
展开全部
写那么麻烦干什么呢,看我的!
Book[] books = { new Book("j2me",12), new Book("j2se",5), new Book("j2ee",22) };
Arrays.sort (books, new Comparator<Book> ()
{
@Override
public int compare ( Book o1, Book o2 )
{
if (o1.getPrice() > o2.getPrice() )
{
return 1;
}
else if (o1.getPrice() < o2.getPrice() )
{
return -1;
}
else
{
return 0;
}
}
});
展开全部
implements Comparator;
重写int compareTo(Book b){
return this.price - b.getPrice();
}
然后Collentions.sort(bookList);
重写int compareTo(Book b){
return this.price - b.getPrice();
}
然后Collentions.sort(bookList);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
import java.util.Arrays;
public class TreeSet1
{
public static void main(String[] args)
{
Book[] books = {new Book("j2me",12),new Book("j2se",5),new Book("j2ee",22)};
Arrays.sort(books);
System.out.println(Arrays.toString(books));
}
}
class Book implements Comparable<Book>
{
private String name;
private int price;
@Override
public String toString()
{
return "Book [name=" + name + ", price=" + price + "]";
}
public Book(String name, int price)
{
super();
this.name = name;
this.price = price;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
@Override
public int compareTo(Book o)
{
return this.getPrice() - o.getPrice();
}
}
public class TreeSet1
{
public static void main(String[] args)
{
Book[] books = {new Book("j2me",12),new Book("j2se",5),new Book("j2ee",22)};
Arrays.sort(books);
System.out.println(Arrays.toString(books));
}
}
class Book implements Comparable<Book>
{
private String name;
private int price;
@Override
public String toString()
{
return "Book [name=" + name + ", price=" + price + "]";
}
public Book(String name, int price)
{
super();
this.name = name;
this.price = price;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getPrice()
{
return price;
}
public void setPrice(int price)
{
this.price = price;
}
@Override
public int compareTo(Book o)
{
return this.getPrice() - o.getPrice();
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
重写Comparator接口
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询