gpt4 book ai didi

java - 如何在Java升序中按内部值对对象排序?

转载 作者:行者123 更新时间:2023-12-01 16:36:39 25 4
gpt4 key购买 nike

我有包含数据的对象列表,如Name(String)和Timestamp(Long)。我试图基于时间戳按升序对这些对象进行排序。

MyCode.java

import java.util.ArrayList;
import java.util.Collections;

class Friend
{
long time;
String name;
Friend(long t,String n)
{
time=t;
name=n;
}
}


public class Practice4 {
public static void main(String[] args) {
long l1=1590065750535l;
long l2=1590065760674l;
long l3=1590065784567l;
long l4=1590065760674l;

Friend f[]=new Friend[4];

f[0]=new Friend(l1,"A");
f[1]=new Friend(l3,"B");
f[2]=new Friend(l2,"C");
f[3]=new Friend(l4,"D");

ArrayList<Friend> list=new ArrayList<Friend>();
list.add(f[0]); list.add(f[1]); list.add(f[2]); list.add(f[3]);

Collections.sort(list); //error
System.out.println(list);
}
}


如何按时间戳对这些Friend对象排序并显示它们?

最佳答案

此代码解决了问题。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

class Friend
{
long time;
String name;
Friend(long t,String n)
{
time=t;
name=n;
}
}


public class Practice4 {
public static void main(String[] args) {
long l1=1590065750535l;
long l2=1590065760674l;
long l3=1590065784567l;
long l4=1590065760674l;

Friend f[]=new Friend[4];

f[0]=new Friend(l1,"A");
f[1]=new Friend(l3,"B");
f[2]=new Friend(l2,"C");
f[3]=new Friend(l4,"D");

ArrayList<Friend> list=new ArrayList<Friend>();
for(int i=0;i<f.length;i++)
list.add(f[i]);

Collections.sort(list,new Comparator<Friend>() {

public int compare(Friend arg0, Friend arg1) {

return (int) (arg0.time - arg1.time);
}
});

for(Friend l: list)
{
System.out.println("Name: "+l.name+", Time: "+l.time);
}
}
}

关于java - 如何在Java升序中按内部值对对象排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61935580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com