1.新建项目,新建Man类,添加属性
2.在代码编辑区域右键,选中source,自动生成setter,getter方法,以及构造函数(类似操作,选中generate constructor using field...)
3.勾选相应的属性,确认即可,很方便。
结果如下图:
Man.java代码如下:
1 public classMan {2
3 privateString name;4 publicString getName() {5 returnname;6 }7 public voidsetName(String name) {8 this.name =name;9 }10 public intgetHeight() {11 returnheight;12 }13 public void setHeight(intheight) {14 this.height =height;15 }16 private intheight;17
18 public Man(String name, intheight) {19 super();20 this.name =name;21 this.height =height;22 }23
24
25
26 }
新建Test.java
添加代码:
importjava.util.ArrayList;public classTest {public static voidmain(String[] args) {
ArrayList 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 importjava.util.Comparator;2
3 public class Compare implementsComparator{4
5 public intcompare(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代码:
importjava.util.ArrayList;importjava.util.Collections;public classTest {public static voidmain(String[] args) {
ArrayList 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=newCompare();
Collections.sort(arr, comparator);for (int i=0;i
Man user_temp=(Man)arr.get(i);
System.out.println(user_temp.getName()+","+user_temp.getHeight());
}
}
}
View Code
项目结构: