发布:2023/12/7 15:41:14作者:大数据 来源:大数据 浏览次数:464
java排序尽量使用系统自带的比较器
1 2 3 4 5 6 |
Comparator<Athlete> compareByTime = new Comparator<Athlete>() { @Override public int compare(Athlete a1, Athlete a2) { return Double.compare(a1.getTime(), a2.getTime()); } }; |
而使用如下比较法可能出现异常
1 2 3 4 5 6 |
if (a1.getTime() > a2.getTime()) { return 1; } else if (a2.getTime() > a1.getTime()) { return -1; } return 0; |
然后进行排序:
1 |
Collections.sort(athletes, compareByTime); |
在多层for循环遍历时,尽量先进行条件判断,然后进行层次递进,否则可能影响效率。
如下4层for
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
for(int a:list1){ for(int b:lsit2){ for(int c:list3){ for(int d:list4){ if(a==1&&b==2&&c==3&&d==4){ //.... } } } } } for(int a:list1){ if(a==1){ for(int b:lsit2){ if(b==2){ for(int c:list3){ //.... for(int d:list4){ if(a==1&&b==2&&c==3&&d==4){ //.... } } } }} } } |
对比如上。第二种优于一种。
java内部类创建和实例化 java可以直接访问内部类成员
1 2 3 4 5 6 7 8 |
Student student = new Student("jone", 22); student.print(); Student.Inner inner = student.new Inner("person"); inner.printAllName(); Student.InnerStatic innerStatic=new Student.InnerStatic(); innerStatic.printStaticName(); |
C# 内部类只能访问外部类static或外部类引用的对象
1 2 3 4 5 6 7 8 9 10 11 |
Console.WriteLine("Hello World!"); Student student = new Student(); student.Name = "student"; student.print(); Student.Inner inner = new Student.Inner(); inner.InnerName = "student inner"; inner.print(); Student.InnerStatic.InnerStaticName = "student inner static"; Student.InnerStatic.print(); |
© Copyright 2014 - 2025 柏港建站平台 ejk5.com. 渝ICP备16000791号-4