Discuss / Java / 截取相同等级字符后面的数字作比较

截取相同等级字符后面的数字作比较

Topic source
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class Test {
    public static void main(String[] args) {
        Queue<User> q = new PriorityQueue<>();
        q.offer(new User("Bob", "A1"));
        q.offer(new User("Alice", "A2"));
        q.offer(new User("Boss", "V1"));
        q.offer(new User("May", "V2"));
        q.offer(new User("Jobs", "A10"));
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
        System.out.println(q.poll());
    }
}

class User implements Comparable {
    public final String name;
    public final String number;
    
    public User(String name, String number) {
        this.name = name;
        this.number = number;
    }
    
    public String toString() {
        return name + "/" + number;
    }

    @Override
    public int compareTo(Object o) {
        User u = (User)o;
        if (this.number.charAt(0) == u.number.charAt(0)) {
            return Integer.parseInt(this.number.substring(1)) > Integer.parseInt(u.number.substring(1)) ? 1 : -1;
        }
        if (this.number.charAt(0) == 'V') {
            return -1;
        } else {
            return 1;
        }
    }
}

  • 1

Reply