From 76fc7821303e6edfc0715fe0a74bc4a758d7faf7 Mon Sep 17 00:00:00 2001 From: buuoltwo Date: Thu, 12 Dec 2024 16:04:39 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DcompareTo=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E4=B8=8D=E6=AD=A3=E7=A1=AE=E5=AE=9E=E7=8E=B0=E5=AF=BC=E8=87=B4?= =?UTF-8?q?=E4=BA=A7=E7=94=9F=E7=9B=B8=E5=90=8C=E5=AF=B9=E8=B1=A1=EF=BC=8C?= =?UTF-8?q?=E8=BF=9B=E8=80=8C=E5=AF=BC=E8=87=B4set=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E4=B8=A2=E5=A4=B1=E5=AF=B9=E8=B1=A1=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/github/hcsp/polymorphism/User.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/hcsp/polymorphism/User.java b/src/main/java/com/github/hcsp/polymorphism/User.java index 7a601df..6220af6 100644 --- a/src/main/java/com/github/hcsp/polymorphism/User.java +++ b/src/main/java/com/github/hcsp/polymorphism/User.java @@ -47,7 +47,10 @@ public int hashCode() { /** 老板说让我按照用户名排序 */ @Override public int compareTo(User o) { - return name.compareTo(o.name); + if(name.compareTo(o.name) == 0) { + return id.compareTo(o.id); + } + return name.compareTo(o.name); } public static void main(String[] args) { @@ -56,7 +59,7 @@ public static void main(String[] args) { new User(100, "b"), new User(10, "z"), new User(1, "a"), - new User(2000, "a")); + new User(2000, "a2")); TreeSet treeSet = new TreeSet<>(users); // 为什么这里的输出是3?试着修复其中的bug System.out.println(treeSet.size());