有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java排序类的arraylist

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,所以我在使用集合时遇到了一个问题。sort(),我该如何进行排序?和你有什么建议使这个计划更好吗?这只是我在做的一个愚蠢的项目,因为每周我都和朋友们去踢足球,我想为什么不为我们的球队制定一个计划呢。为了提高它,我想把“puneggio”的价值放在技能上,用它来选择球员将要去的球队,但是现在如果它随机选择的话是不够的


共 (1) 个答案

  1. # 1 楼答案

    我相信这就是你要找的。您可以指定自己的比较器,而无需实际实现可比较接口

    • 第一个参数-要排序的列表
    • 第二个参数-指定要排序的Giocatore类字段的比较器
    public void SortGiocatori() {
        Collections.sort(giocatori, Comparator.comparing(Giocatore::getPunteggio));
    }