对类的arraylist进行排序

xpszyzbs  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(249)

此问题已在此处找到答案

按属性对自定义对象的arraylist排序(29个答案)
四天前关门。

public class Giocatore {
private String nome;
private int punteggio;

public Giocatore(String nome, int punteggio) {
    this.nome = nome;
    this.punteggio = punteggio;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public int getPunteggio() {
    return punteggio;
}

public void setPunteggio(int punteggio) {
    this.punteggio = punteggio;
}

@Override
public String toString() {
    return "Giocatori [nome=" + nome + ", punteggio=" + punteggio + "]";
}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

public class CreazioneSquadre {

private ArrayList<Giocatore> giocatori;
private String [] squadraA;
private String [] squadraB;

public CreazioneSquadre() {
    giocatori = new ArrayList<Giocatore>();
    squadraA = new String[5];
    squadraB = new String[5];
}

public void creazioneGiocatori() {
    Random random = new Random();
    giocatori.add(new Giocatore("Giocatore1" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore2" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore3" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore4" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore5" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore6" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore7" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore8" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore9" , random.nextInt(10 - 1) + 1));
    giocatori.add(new Giocatore("Giocatore10" , random.nextInt(10 - 1) + 1));
}

public void SortGiocatori() {

}

public void stampa() {
    for (int i = 0; i < giocatori.size(); i++) {
        System.out.println((i+1) + ") Nome: " + giocatori.get(i).getNome() + " Punteggio: " + giocatori.get(i).getPunteggio());
    }
}   
}

嗨,伙计们,我正在尝试制作一个程序,使我成为一个足球队,这是我将改进的第一个版本。问题在哪里?我会对arraylist giocatori进行排序,但它是一个类的arraylist,所以我在使用collections.sort()时遇到了一个问题,如何对其进行排序?而且。。。你有什么建议使这个计划更好吗?这只是我在做的一个愚蠢的项目,因为每周我都和朋友们去踢足球,我想为什么不为我们的球队制定一个计划呢。为了提高它,我想把“puneggio”的价值放在技能上,用它来选择球员将要去的球队,但是现在如果它随机选择的话是不够的

nimxete2

nimxete21#

我相信这就是你要找的。您可以指定自己的比较器,而无需实际实现可比较接口。
第一个参数-要排序的列表。
第二个参数-指定 Giocatore 要排序的类。

public void SortGiocatori() {
    Collections.sort(giocatori, Comparator.comparing(Giocatore::getPunteggio));
}

相关问题