ArrayList元素的排序java 集合

it2024-10-15  22

1.新建项目,新建Man类,添加属性

2.在代码编辑区域右键,选中source,自动生成setter,getter方法,以及构造函数(类似操作,选中generate constructor using field...)

3.勾选相应的属性,确认即可,很方便。

 

结果如下图:

Man.java代码如下:

1 public class Man { 2 3 private String name; 4 public String getName() { 5 return name; 6 } 7 public void setName(String name) { 8 this.name = name; 9 } 10 public int getHeight() { 11 return height; 12 } 13 public void setHeight(int height) { 14 this.height = height; 15 } 16 private int height; 17 18 public Man(String name, int height) { 19 super(); 20 this.name = name; 21 this.height = height; 22 } 23 24 25 26 }

新建Test.java

添加代码:

import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<Man> arr=new ArrayList<>();//新建动态链表 //创建4个对象 Man man_exam1=new Man("高个子",185); Man man_exam2=new Man("中个子",175); Man man_exam3=new Man("矮个子",165); Man man_exam4=new Man("高个子",195); //随意添加到动态数组里面 arr.add(man_exam1); arr.add(man_exam4); arr.add(man_exam3); //打印查看 for (Man man : arr) { System.out.println(man.getName()+man.getHeight()); } } View Code

运行输出如下结果:

高个子185高个子195矮个子165

可以看到是乱序的。现在对其排序:

新建类:Compare.java

 

 

 代码:

1 import java.util.Comparator; 2 3 public class Compare implements Comparator{ 4 5 public int compare(Object obj0, Object obj1) { 6 Man s1=( Man)obj0; 7 Man s2=( Man)obj1; 8 9 if(s1.getHeight()<=s2.getHeight()) 10 return 1; 11 12 return -1; 13 } 14 15 } View Code

在Test.java中加入如下代码(对象已经存放在动态数组arr里面,执行如下代码后arr中已经是排好序的):

Compare comparator=new Compare(); Collections.sort(arr, comparator);

  

 

 最终完整版Test.java代码:

import java.util.ArrayList; import java.util.Collections; public class Test { public static void main(String[] args) { ArrayList<Man> arr=new ArrayList<>();//新建动态链表 //创建4个对象 Man man_exam1=new Man("高个子",185); Man man_exam2=new Man("中个子",175); Man man_exam3=new Man("矮个子",165); Man man_exam4=new Man("高个子",195); //随意添加到动态数组里面 arr.add(man_exam1); arr.add(man_exam4); arr.add(man_exam3); //打印查看 for (Man man : arr) { System.out.println(man.getName()+man.getHeight()); } System.out.println("排序后"); Compare comparator=new Compare(); Collections.sort(arr, comparator); for (int i=0;i<arr.size();i++){ Man user_temp=(Man)arr.get(i); System.out.println(user_temp.getName()+","+user_temp.getHeight()); } } } View Code

项目结构:

 

转载于:https://www.cnblogs.com/bysking/p/9210748.html

最新回复(0)