How to sort an attribute of an object using Collections

后端 未结 6 902
眼角桃花
眼角桃花 2020-12-03 11:52

Good day!

I have an object student with the following attributes:

class Student
    String name
    Date birthday

I used arrayList

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 12:07

    Hi this is a sample that can help you to understand

    package de.vogella.algorithms.sort.standardjava;
    
    import java.util.Comparator;
    
    public class MyIntComparable implements Comparator{
    
        @Override
        public int compare(Integer o1, Integer o2) {
            return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
        }
    }
    
    
    package de.vogella.algorithms.sort.standardjava;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class Simple2 {
        public static void main(String[] args) {
            List list = new ArrayList();
            list.add(5);
            list.add(4);
            list.add(3);
            list.add(7);
            list.add(2);
            list.add(1);
            Collections.sort(list, new MyIntComparable());
            for (Integer integer : list) {
                System.out.println(integer);
            }
        }
    }
    

提交回复
热议问题