zoukankan      html  css  js  c++  java
  • 容器集合

    怎么给集合内的数按顺序排序
    
    package test2;
    
    public class Book implements Comparable<Book> {
        private String name;
        private double price;
    
        public Book() {
            super();
        }
    
        public Book(String name, double price) {
            super();
            this.name = name;
            this.price = price;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Book [name=" + name + ", price=" + price + "]";
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Book other = (Book) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }
    
        public double getPrice() {
            return price;
        }
    
        public void setPrice(double price) {
            this.price = price;
        }
    
        @Override
        public int compareTo(Book o) {
            if (this.price > o.getPrice()) {
                return 1;
            }
            if (this.price == o.getPrice()) {
                return 0;
            }
            return -1;
        }
    }
    package test2;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * Comparable
     * @author Administrator
     */
    public class Test6 {
    
        public static void main(String[] args) {
            List<Book> list = new ArrayList<Book>();
            list.add(new Book("Java从入门到放弃", 78));
            list.add(new Book("Oracle数据库详解", 56));
            list.add(new Book("HTML入门", 3));
            list.add(new Book("三国演义", 108));
            Collections.sort(list);
            Collections.reverse(list);
            
            System.out.println(list);
        }
    
    }

    这样就可以按照书本后面的标价进行排序,从而获得一个价格从高到低的数组集合。

  • 相关阅读:
    Oracle sql优化
    Oracle解决锁表语句与批量生成解锁语句
    使用Spring Task轻松完成定时任务
    oralce数据表空间满了
    关于出现 org.apache.commons.lang.exception.NestableRuntimeException的解决方法
    linux根分区满了如何处理,查找大文件方法
    bt协议详解 基础篇(上)
    如何做一个开心的程序员
    程序猿是如何解决SQLServer占CPU100%的
    SqlServer索引的原理与应用
  • 原文地址:https://www.cnblogs.com/F9801/p/9027401.html
Copyright © 2011-2022 走看看