实现Comparable接口,进行排序

心动Oath

心动Oath

2021-01-14

import

java.util.ArrayList;

import

java.util.Collections;

import

java.util.List;

public

class

Bookimplements

Comparable{

/*编写一个类Book,具有name,price,press,author属性.然后创建5个对象放入ArrayList中,并实现按照price大小排序(使用Comparable接口排序),

然后遍历ArrayList输出每个Book对象。*/

private

Stringname;

private

float

price;

private

Stringpress;

private

Stringauthor;

//构造方法

public

Book(Stringname,float

price,Stringpress,Stringauthor){

this

.name=name;

this

.price=price;

this

.press=press;

this

.author=author;

System.out.println(name.toString());

}

@SuppressWarnings

("unchecked"

)

public

static

void

main(String[]args){

List<Book>list=new

ArrayList<Book>();

Bookb1=new

Book("java1"

,25f,"不错的书"

,"LY1"

);

Bookb2=new

Book("java2"

,26f,"不错的书"

,"LY2"

);

Bookb3=new

Book("java3"

,50f,"不错的书"

,"LY3"

);

Bookb4=new

Book("java4"

,20f,"不错的书"

,"LY4"

);

Bookb5=new

Book("java5"

,15f,"不错的书"

,"LY5"

);

list.add(b1);

list.add(b2);

list.add(b3);

list.add(b4);

list.add(b5);

Collections.sort(list);

for

(int

i=0

;i<list.size();i++){

Bookbook=(Book)list.get(i);

System.out.println(book);

}

}

//重写

public

int

compareTo(Objectobj){

Bookp=(Book)obj;

if

(p.price>this

.price){

return

1

;

}

else

if

(p.price<this

.price){

return

-1

;

}

else

{

return

0

;

}

}

//重写toString方法

public

StringtoString(){//这上是重写了本类的toString方法,对系统自带的其它字段的toString方法无效

return

"书名:"

+this

.name+",价格:"

+this

.price+",说明:"

+this

.press+",作者:"

+this

.author;

}

}

//.sort(List)方法,当然还可能使用java.util.Arrays.sort(数组),那样就必须把//list转化为数组,由于本例使用Collections.sort(List)已经足够,另一方法,大家可//以尝试自已使用.

精彩推荐

粤ICP备16095388号-1