对类的arraylist进行排序

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

此问题已在此处找到答案

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

  1. public class Giocatore {
  2. private String nome;
  3. private int punteggio;
  4. public Giocatore(String nome, int punteggio) {
  5. this.nome = nome;
  6. this.punteggio = punteggio;
  7. }
  8. public String getNome() {
  9. return nome;
  10. }
  11. public void setNome(String nome) {
  12. this.nome = nome;
  13. }
  14. public int getPunteggio() {
  15. return punteggio;
  16. }
  17. public void setPunteggio(int punteggio) {
  18. this.punteggio = punteggio;
  19. }
  20. @Override
  21. public String toString() {
  22. return "Giocatori [nome=" + nome + ", punteggio=" + punteggio + "]";
  23. }
  24. }
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.Collections;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Random;
  31. public class CreazioneSquadre {
  32. private ArrayList<Giocatore> giocatori;
  33. private String [] squadraA;
  34. private String [] squadraB;
  35. public CreazioneSquadre() {
  36. giocatori = new ArrayList<Giocatore>();
  37. squadraA = new String[5];
  38. squadraB = new String[5];
  39. }
  40. public void creazioneGiocatori() {
  41. Random random = new Random();
  42. giocatori.add(new Giocatore("Giocatore1" , random.nextInt(10 - 1) + 1));
  43. giocatori.add(new Giocatore("Giocatore2" , random.nextInt(10 - 1) + 1));
  44. giocatori.add(new Giocatore("Giocatore3" , random.nextInt(10 - 1) + 1));
  45. giocatori.add(new Giocatore("Giocatore4" , random.nextInt(10 - 1) + 1));
  46. giocatori.add(new Giocatore("Giocatore5" , random.nextInt(10 - 1) + 1));
  47. giocatori.add(new Giocatore("Giocatore6" , random.nextInt(10 - 1) + 1));
  48. giocatori.add(new Giocatore("Giocatore7" , random.nextInt(10 - 1) + 1));
  49. giocatori.add(new Giocatore("Giocatore8" , random.nextInt(10 - 1) + 1));
  50. giocatori.add(new Giocatore("Giocatore9" , random.nextInt(10 - 1) + 1));
  51. giocatori.add(new Giocatore("Giocatore10" , random.nextInt(10 - 1) + 1));
  52. }
  53. public void SortGiocatori() {
  54. }
  55. public void stampa() {
  56. for (int i = 0; i < giocatori.size(); i++) {
  57. System.out.println((i+1) + ") Nome: " + giocatori.get(i).getNome() + " Punteggio: " + giocatori.get(i).getPunteggio());
  58. }
  59. }
  60. }

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

nimxete2

nimxete21#

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

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

相关问题