Java 在运行应用程序时,排序的ArrayList不显示为已排序
我有一个Java 在运行应用程序时,排序的ArrayList不显示为已排序,java,android,firebase-realtime-database,collections,Java,Android,Firebase Realtime Database,Collections,我有一个ArrayList,我使用compareTo对其进行了排序。当我运行这个程序时,我会按照我在列表中输入项目的顺序得到一个列表,即使我知道我已经对它进行了排序 我在ArrayList上调用了Collections.sort(),但什么也没发生。当我执行Collections.reverse()操作时,列表按我最初输入的顺序向后显示 public int compareTo(LeaderPlayers players) { int compareTo=((Leader
ArrayList
,我使用compareTo
对其进行了排序。当我运行这个程序时,我会按照我在列表中输入项目的顺序得到一个列表,即使我知道我已经对它进行了排序
我在ArrayList
上调用了Collections.sort()
,但什么也没发生。当我执行Collections.reverse()
操作时,列表按我最初输入的顺序向后显示
public int compareTo(LeaderPlayers players)
{
int compareTo=((LeaderPlayers)players).getScore();
return this.score-compareTo;
}
这就是我比较并使用Collections.sort()
对列表排序的方式
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> workshopParticipants = new ArrayList<String>();
workshopParticipants.add("Christine");
workshopParticipants.add("Marty");
workshopParticipants.add("Tom");
workshopParticipants.add("JeanMarie");
workshopParticipants.add("Daniel");
Collections.sort(workshopParticipants);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RecyclerViewAdapter(this, workshopParticipants);
adapter.setClickListener(this);
mRecyclerView.setAdapter(adapter);
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList workshopParticipants=新建ArrayList();
工作场所参与者。添加(“Christine”);
工作区参与者。添加(“Marty”);
工作区参与者。添加(“Tom”);
工作场所参与者。添加(“JeanMarie”);
工作区参与者。添加(“Daniel”);
集合。排序(工作区参与者);
mRecyclerView=(RecyclerView)findViewById(R.id.recycler\u视图);
mRecyclerView.setLayoutManager(新的LinearLayoutManager(this));
适配器=新的RecycleServiceAdapter(此为工作区参与者);
adapter.setClickListener(此);
mRecyclerView.setAdapter(适配器);
在RecyclerView
中,参与者按克里斯蒂娜、马蒂、汤姆、詹玛丽、丹尼尔的顺序出现
我希望它们按点数的顺序出现,我在这里没有显示。我已经清楚地对其进行了排序,但它没有显示为已排序。这可能是因为我使用了
RecyclerView
吗?您正在对玩家的姓名进行排序String
您需要对具有他得分
值,而不仅仅是他们的名字。假设你有一个班级:
class LeaderPlayers实现了可比较的{
字符串名;
智力得分;
...
}
您需要执行以下操作:
List players=new ArrayList();
添加(新的领导层(“Christine”,30));
玩家。添加(新的领导层(“玛尔塔”,20))
添加(新的领导层(“Alice”,10));
集合。排序(玩家);
使用Java-8,您可以执行以下操作:
ArrayList<String> FinalList = new ArrayList<String>();
FinalList= workshopParticipants.stream().sorted().collect(Collectors.toCollection(ArrayList::new));
System.out.println(FinalList);
ArrayList FinalList=new ArrayList();
FinalList=workshopParticients.stream().sorted().collect(Collectors.toCollection(ArrayList::new));
System.out.println(FinalList);
WorkshopParticipants是一个字符串列表,您的比较函数在这里没有考虑排序,PS为什么要将玩家强制转换为LEaderPlayer?您可能需要执行类似workshopParticipans stream()的操作。map(str->new LEaderPlayer(str)).sorted().collect(Collectors.toList())即使我不知道你从哪里得到的分数在这种情况下