Java中基于给定主类实现自定义对象列表的Collections.sort排序
问题描述
现有一项作业要求基于给定主类实现对象列表的打印与排序,主类代码如下:
public static void main(String[] args) throws IOException { ArrayList<LoaiPhong> ds = new ArrayList<>(); Scanner in = new Scanner(new File("xx.in")); int n = Integer.parseInt(in.nextLine()); while(n-- > 0){ ds.add(new LoaiPhong(in.nextLine())); } Collections.sort(ds); // 仅对对象列表排序,但当前无有效排序逻辑 for(LoaiPhong tmp : ds){ System.out.println(tmp); } } static class LoaiPhong { String line; public LoaiPhong(String line) { this.line = line; } }
需要修改LoaiPhong类,实现按自定义属性排序,同时让列表打印能输出对象的有效信息。
解决方案
方式一:让LoaiPhong实现Comparable接口(默认排序规则)
通过实现Comparable<LoaiPhong>接口并重写compareTo方法,定义类的默认排序逻辑。同时必须重写toString方法,否则打印对象时会输出默认的哈希值而非有效属性内容。
修改后的LoaiPhong类示例:
static class LoaiPhong implements Comparable<LoaiPhong> { String line; // 可根据业务需求拆分line为具体属性,比如假设line格式为"房型 价格" String roomType; int price; public LoaiPhong(String line) { this.line = line; // 示例:拆分字符串获取属性 String[] parts = line.split(" "); this.roomType = parts[0]; this.price = Integer.parseInt(parts[1]); } // 重写compareTo定义排序逻辑,示例:按价格升序,价格相同则按房型名称升序 @Override public int compareTo(LoaiPhong o) { if (this.price != o.price) { return Integer.compare(this.price, o.price); } return this.roomType.compareTo(o.roomType); } // 重写toString实现对象的友好打印 @Override public String toString() { return line; // 也可返回格式化内容,比如"房型:" + roomType + ",价格:" + price } }
compareTo方法返回规则:
- 返回负数:当前对象排在参数对象之前
- 返回0:两个对象排序位置相同
- 返回正数:当前对象排在参数对象之后
方式二:使用自定义Comparator(灵活多规则排序)
如果不想修改LoaiPhong类结构,或者需要多种排序规则,可以在调用Collections.sort时传入自定义Comparator对象:
// 示例:按line字符串长度升序排序 Collections.sort(ds, new Comparator<LoaiPhong>() { @Override public int compare(LoaiPhong a, LoaiPhong b) { return Integer.compare(a.line.length(), b.line.length()); } }); // Java 8及以上可用Lambda简化写法 Collections.sort(ds, (a, b) -> Integer.compare(a.line.length(), b.line.length()));
内容的提问来源于stack exchange,提问作者Pson
相关产品推荐
相关产品推荐

