(一道面試題)對一個對象數組進組排序,試題數組

來源:互聯網
上載者:User

(一道面試題)對一個對象數組進組排序,試題數組

這是我在一個面試初級工程師的時候遇到的一個問題,覺得在項目中都沒怎麼遇到.

一.編寫一個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()+" ");}}}

 四.實驗結果:

五.總結:這個主要是對數組熟悉程度的一個考察.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.