第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在Java中對(duì)對(duì)象數(shù)組進(jìn)行排序?

如何在Java中對(duì)對(duì)象數(shù)組進(jìn)行排序?

如何在Java中對(duì)對(duì)象數(shù)組進(jìn)行排序?我的數(shù)組不包含任何字符串。但它包含對(duì)象引用。每個(gè)對(duì)象引用都通過toString方法返回name,id,author和publisher。public String toString() {         return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n");}現(xiàn)在我需要按名稱對(duì)對(duì)象數(shù)組進(jìn)行排序。我知道如何排序,但我不知道如何從對(duì)象中提取名稱并對(duì)它們進(jìn)行排序。
查看完整描述

3 回答

?
寶慕林4294392

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊

Java 8


使用lambda表達(dá)式

Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));

Test.java

public class Test {

    public static void main(String[] args) {

        MyType[] myTypes = {
                new MyType("John", 2, "author1", "publisher1"),
                new MyType("Marry", 298, "author2", "publisher2"),
                new MyType("David", 3, "author3", "publisher3"),
        };

        System.out.println("--- before");
        System.out.println(Arrays.asList(myTypes));
        Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));
        System.out.println("--- after");
        System.out.println(Arrays.asList(myTypes));

    }}

MyType.java

public class MyType {

    public String name;
    public int id;
    public String author;
    public String publisher;

    public MyType(String name, int id, String author, String publisher) {
        this.name = name;
        this.id = id;
        this.author = author;
        this.publisher = publisher;
    }

    @Override
    public String toString() {
        return "MyType{" +
                "name=" + name + '\'' +
                ", id=" + id +
                ", author='" + author + '\'' +
                ", publisher='" + publisher + '\'' +
                '}' + System.getProperty("line.separator");
    }}

輸出:

--- before[MyType{name=John', id=2, author='author1', publisher='publisher1'}, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}, MyType{name=David', id=3, author='author3', publisher='publisher3'}]--- after[MyType{name=David', id=3, author='author3', publisher='publisher3'}, MyType{name=John', id=2, author='author1', publisher='publisher1'}, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}]

使用方法引用

Arrays.sort(myTypes, MyType::compareThem);

其中,compareThem已經(jīng)在加入MyType.java

public static int compareThem(MyType a, MyType b) {
    return a.name.compareTo(b.name);}


查看完整回答
反對(duì) 回復(fù) 2019-08-08
  • 3 回答
  • 0 關(guān)注
  • 2018 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)