package tushu; import java.util.Comparator; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { TreeMap<String,Book> map=new TreeMap<String,Book>(new MyComparator()); map.put("B45678", new Book("B45678","钢铁是怎样连城的","保尔",56)); map.put("B678", new Book("B678","世界时平的","保尔",56)); map.put("D89", new Book("D89","java编程思想","kobe",56)); map.put("A15678", new Book("A15678","高等数学","joms",56)); System.out.println(map); } } class Book { String bookno; String bookName; String author; int price; public String getBookno() { return bookno; } public void setBookno(String bookno) { this.bookno = bookno; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Book [bookno=" + bookno + ", bookName=" + bookName + ", author=" + author + ", price=" + price + "]"; } public Book(String bookno, String bookName, String author, int price) { super(); this.bookno = bookno; this.bookName = bookName; this.author = author; this.price = price; } } class MyComparator implements Comparator<String>{ @Override public int compare(String o1, String o2) { if(o1.length()==o2.length()){ return o1.compareTo(o2); } return o1.length()-o2.length(); } }
时间: 2024-10-12 13:05:26