图书馆管理系统(无界面)

来源:互联网 发布:淘宝如何设置购买选项 编辑:程序博客网 时间:2024/05/16 15:58

    Ok... I just delete all words I wrote in Chinese... The more writing in English is done, the better you write... Just got it from a predecessor's blog and I should do it right now!
    I really appreciated the great class library which free me from underlying consideration and make it possible to take and use at once~

1. Generic arraylist:
    This is the third time that I have used it. It is simplified and effective. First I wrote a class named Book. And then "List<Book> books = new ArrayList<Book>();"

2. Comparator:
    This is the most significant part that I learned from this project.

    public void sortTheList() {
        System.out.println("Please input the order of the following attributions which you would like to use to sort:");
        System.out.println(" 1. Name\n 2. Price\n");
        public void sortTheList() {
            Scanner keyboard = new Scanner(System.in);
            Comparator<Book> cmp = null;       // Here we initialize a comparator to use
            switch (keyboard.nextInt()) {
            case 1:
                   cmp = new Comparator<Book>() { 
                          public int compare(Book b1, Book b2) {
                                   if (!b1.name.equalsIgnoreCase(b2.name))
                                        return b1.name.compareTo(b2.name); 
                                        // use "compareTo"method for String
                                   else
                                         return 0;
                          }
                };
            break;
            case 2:
                   cmp = new Comparator<Book>() {
                          public int compare(Book b1, Book b2) {
                                   if (b1.price != b2.price)
                                          return (int) (b1.price - b2.price);
                                          // take care about the return type of the constructor
                                    else
                                           return 0;
                          }
                   };
           break;
       }
       Collections.sort(books, cmp); 
       //Everthing you need to do else is directly invoking the method "Collections.sort(List list,Comparator cmp)"
    }

3.a class impletementing Serializable and use IO about objects

    static class Book implements Serializable

    "static" is written down because the eclipse asked to... The root cause maybe that it is necessary to make the object from this class static so that they can be read or written... (NEED REVISING)

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
    while (true) {
    books.add((Book) in.readObject());

    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));
    for (Book tmp : books) {
    out.writeObject(tmp);

Above are two streams used to read and write objects of Book. SO CONVENIENT~

 

原创粉丝点击