JAVA程序,N个射击选手,根据射击得分从小到大排名,射击得分一样则根据编号从小到大排名,很简单的一道题,可以用跳表做。
JUC包下面提供跳表的List和Map结构。
如下:
ConcurrentSkipListSet
ConcurrentSkipListMap
设计射击选手类:
package com.entity;
import lombok.Data;
import java.io.Serializable;
/**
* (Shooter)实体类
*
* @author makejava
* @since 2021-05-11 11:37:36
*/
@Data
public class Shooter implements Serializable,Comparable{
private static final long serialVersionUID = -74685728705540553L;
private String name;
private int score;
private long id;
public Shooter(String name, int score, long id) {
this.name = name;
this.score = score;
this.id = id;
}
@Override
public String toString() {
return "Shooter{" +
"name='" + name + '\'' +
", score=" + score +
", id=" + id +
'}';
}
//做HashMap的key时,需重写equals
@Override
public boolean equals(Object o)
{
if(!(o instanceof Shooter))
{
return false;
}
if(!this.getName().equals(((Shooter) o).getName()))
{
return false;
}
if(this.getScore()!=((Shooter) o).getScore())
{
return false;
}
return true;
}
//做HashMap的key时,需重写hashCode
@Override
public int hashCode()
{
return ((Long)this.id).intValue();
}
@Override
public int compareTo(Object o) {
Shooter o2=(Shooter)o;
if(this.getScore()==o2.getScore())
{
return this.getId()>o2.getId()?1:-1;
}
return this.getScore()>o2.getScore()?1:-1;
}
}
一:ConcurrentSkipListSet
public static void main(String []args)
{
//Skip List类型
ConcurrentSkipListSet<Shooter>
shooters=new ConcurrentSkipListSet<Shooter>();
for(int i=0;i<10;i++)
{
shooters.add(new Shooter("姓名"+(i+1),
new Random().nextInt(10),i+1));
}
for(Shooter shooter:shooters)
{
System.out.println(shooter.toString());
}
}
打印:
Shooter{name='姓名10', score=1, id=10}
Shooter{name='姓名1', score=2, id=1}
Shooter{name='姓名4', score=2, id=4}
Shooter{name='姓名6', score=2, id=6}
Shooter{name='姓名3', score=5, id=3}
Shooter{name='姓名7', score=7, id=7}
Shooter{name='姓名2', score=8, id=2}
Shooter{name='姓名8', score=8, id=8}
Shooter{name='姓名5', score=9, id=5}
Shooter{name='姓名9', score=9, id=9}
二:ConcurrentSkipListMap
public static void main(String []args)
{
//Skip Map类型
Map<Shooter,String>
shooters=new ConcurrentSkipListMap<Shooter,String>();
for(int i=0;i<10;i++)
{
shooters.put(new Shooter("姓名"+(i+1),
new Random().nextInt(10),i+1),i+"");
}
for(Map.Entry entry:shooters.entrySet())
{
System.out.println(entry.getKey().toString());
}
}
打印:
Shooter{name='姓名9', score=0, id=9}
Shooter{name='姓名3', score=1, id=3}
Shooter{name='姓名4', score=1, id=4}
Shooter{name='姓名2', score=2, id=2}
Shooter{name='姓名7', score=2, id=7}
Shooter{name='姓名1', score=5, id=1}
Shooter{name='姓名8', score=5, id=8}
Shooter{name='姓名10', score=8, id=10}
Shooter{name='姓名5', score=9, id=5}
Shooter{name='姓名6', score=9, id=6}

3490

被折叠的 条评论
为什么被折叠?



