(一道面試題)對一個對象數組進組排序,試題數組
這是我在一個面試初級工程師的時候遇到的一個問題,覺得在項目中都沒怎麼遇到.
一.編寫一個Student對象
public class Student { private String name; private Integer age;/** * @return the name *//** * @return the name */public String getName() { return name;}/** * @param name the name to set */public void setName(String name) { this.name = name;}/** * @return the age */public Integer getAge() { return age;}/** * @param age the age to set */public void setAge(Integer age) { this.age = age;}/*** <p>Title: </p>* <p>Description: </p>* @param name* @param age*/public Student(String name, Integer age) { super(); this.name = name; this.age = age;}/* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) *//* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */}
二.編寫測試類別主要用到得時Collections這個協助工具輔助
1.Collections.sort方法支援對對象進組排序
2.使用方法:只要實現Comparator方法.
3.實現目的:主要是告訴這個方法我要用什麼方式進行對象的排序
4.這裡我將對學生的年齡進行排序,年齡相等的對名字再進行排序
package com.hck.test;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.List;public class ArrayListDemo { public static void main(String[] args) {//建立數組並且添加對象List<Student> slist=new ArrayList<Student>();slist.add(new Student("張三", 28));slist.add(new Student("王五", 23));slist.add(new Student("老六", 27));slist.add(new Student("啊四", 21));slist.add(new Student("大紅", 21));System.out.println("===排序前===");for (Student student:slist) {System.out.print(student.getName()+" ");}System.out.println(); /** * Collections.sort方法支援對對象進組排序 * 使用方法:只要實現Comparator方法. * 這個方法主要是告訴這個方法我要用什麼方式進行對象的排序 * 這裡我將對學生的年齡進行排序,年齡相等的對名字再進行排序 */Collections.sort(slist, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {//大於返回1if(o1.getAge()>o2.getAge()){return 1;}//小於返回-1if(o1.getAge()<o2.getAge()){return -1;}//等於的話比較name的大小//compareTo傳回值也是正數,0,負數//對應的是大於,等於,小於 return(o1.getName().compareTo(o2.getName()));// TODO Auto-generated method stub}});System.out.println("===排序後===");//增強for迴圈語句列印輸出for (Student student:slist) {System.out.print(student.getName()+" ");}}}
四.實驗結果:
五.總結:這個主要是對數組熟悉程度的一個考察.