随机生成10个对象 每个对象都随机生成自带的随机数 按照各自的随机数大小比较排序 按从大到小 把这十个对象打印出
peo类 用于创建对象包括其名称 随机数(hp)
package le;
public class peo{
public String name;
public int hp;
public peo(String name,int hp)
{
this.name=name;
this.hp=hp;
}
public peo()
{
}
public String toString()
{
return name;
}
}
peonode 类 二叉树节点设置 及排序输出 需要导入peo类
package le;
import java.util.ArrayList;
import java.util.List;
import le.peo;
public class peonode {
public peonode leftNode;
public peonode rightNode;
public peo value;
public void add(peo v)
{
if(value==null)
{
value=v;
}
else
{
if((Integer)v.hp<=(Integer)value.hp)
{
if(leftNode==null)
leftNode=new peoNode();
leftNode.add(v);
}
else
{
if(rightNode==null)
rightNode=new peoNode();
rightNode.add(v);
}
}
}
public List order()
{
List sd=new ArrayList<>();
if(rightNode!=null)
{
sd.addAll(rightNode.order());
}
sd.add(value);
if(leftNode!=null)
{
sd.addAll(leftNode.order());
}
return sd;
}
public void list(List h)
{
for(int i=0;i<10;i++)
{
int s=(int)(Math.random()*1000);
h.add(new peo(("hero "+i),s));
}
}
public static void main(String[] args) {
peonode p=new peoNode();
List e =new ArrayList<>();
List o=new ArrayList<>();
List OtherE=new ArrayList<>();
List Othero=new ArrayList<>();
p.list(e);
for (peo object : e) {
p.add(object);
}
System.out.println("Initial:");
for (int k = 0; k < 10; k++) {
o.add("name:"+e.get(k)+"hp:"+e.get(k).hp+"n");
}
System.out.println(o);
OtherE=p.order();
System.out.println("done!");
for (int j = 0; j < 10; j++) {
Othero.add(j+1+" "+"name:"+OtherE.get(j).name+"hp:"+OtherE.get(j).hp+"n");
}
System.out.println(Othero);
}
}
注意两种类类型的类名都调用了 add(); 方法 但是不是同一个 注意看对象类型 什么类型调用该有的方法



