http://t.csdn.cn/IyAC7 (图书管理系统)
前面,我介绍了我的图书管理系统,但是经过学长的批改也是发现了不够好的地方,下面我就来介绍一下我的优化方案。
首先是包名:命名要求包含的所有字符均为小写,同时不能有特殊字符。这是我犯的一处错误。
其次,我在进行查找的时候用的都是for循环从头到尾一个个找(如下:),如果数据小没什么影响,但是既然是图书管理系统,数据是很庞大的,这样的查找方法会造成查找速度很慢。
for (Book book1 : arrayListBook) {//增强for循环
//判断ISBN是否重复
if (book.getISBN().equals(book1.getISBN())) {
System.out.println("该图书已存在!");
}
下面是我的优化方案:
用Map去查。具体是,同样用序列化和反序列化来读写Map文件。
//序列化
public static void serializableISBN(Map<String,Integer> map) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileISBN));
oos.writeObject(map);
//oos.flush();
oos.close(); //释放资源
} catch (Exception e) { //抛异常
e.printStackTrace();
}
}
//反序列化
public static Map<String,Integer> turnSerializableISBN () {
Map<String,Integer> map=new HashMap<>();
try {
if (!fileISBN.exists()) {
fileISBN.createNewFile(); //先判断文件是否存在,如果不存在就先建一个
}
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileISBN));
//这里直接强转集合
map = (Map<String, Integer>) ois.readObject();
ois.close();
} catch (Exception e) {
System.out.println("文件首次创建成功");
}
return map;
}
这样就得到了一个Map,再用它去查:
public static Book getISBNBook(String ISBN){
if (file.exists() == false) {
System.out.println("文件不存在,请先创建文件!");
} else if (file.length() == 0) {
System.out.println("文件中还没添加图书,请先添加!");
} else {
ArrayList<Book> bookArrayList = turnSerializable();
Map<String, Integer> map1 = turnSerializableISBN();
try {
Integer a = map1.get(ISBN);
return bookArrayList.get(a);
} catch (NullPointerException nullPointerException) {
System.out.println("您查找的图书不存在或输入的ISBN有误!!!");
}
/*Integer a = map1.get(ISBN);
if (a == null) {
System.out.println("您查找的图书不存在!");
return null;
} else {
return bookArrayList.get(a);
}
}*/
}
return null;
}
其他功能也类似。
这是目前发现的不足。