【发布时间】:2015-12-08 00:50:07
【问题描述】:
我已经为我的图书馆应用程序设置了 book 类型的 ArrayList。我正在尝试实现的当前功能是编辑一本书的细节。我有一个名为bookID 的变量,所以当我通过ArrayList 调用此方法时,它将是newBook.get(index).getBookID();。有了这些信息,我想检查并做以下事情:
- 存在具有此 ID 的数组元素
- 用新标题更新现有标题
我遇到的问题:
- 循环获取ID所在的索引
- 更新现有标题,并将其替换为新标题
到目前为止我想出了什么:
// Editing book in ArrayList
public void editBook(){
System.out.println("==============================");
// Ensuring array has at least one book
if(newBook.size() > 0){
// Get which part, and book the user would like to edits
System.out.print("Enter Book ID to begin editing: ");
int bookID = sc.nextInt();
System.out.println("Press 1 or 2 to edit.");
System.out.println("1: Edit title");
System.out.println("2: Edit author");
System.out.print("Enter option: ");
int editOption = sc.nextInt();
// Switch statement which will handle editing book
switch(editOption){
case 1:
// New title
System.out.print("Enter new title: ");
String newTitle = sc.nextLine();
sc.next();
// Updates title
newBook.get(position).setTitle(newTitle);
// Prints out title
System.out.println(newBook.get(position).getTitle());
break; // Edit title
上面的代码只是部分代码,下面的任何内容都与问题无关。
【问题讨论】:
-
使用
Map,键入bookId,或者您可以使用Java 8 的新StreamAPI 和filterList,用于example,但使用@987654332 @ 更有效 -
int editOption = sc.nextInt(); ... String newTitle = sc.nextLine();-> Skipping nextLine() after using next(), nextInt() or other nextFoo() methods(我没有阅读您的问题,但这个问题需要更正)。 -
抱歉,我不确定
Map的作用。我还是一年级学生。 -
你知道什么是树形数据结构吗?它有点相似,它允许基于唯一键更快地查找项目。见Collections Trail
-
一种您可能更熟悉的方法是创建一个带有 int 参数 (int bookId) 的方法。您可以使用 for/for-each 循环,如果
newBook.getId() == bookId则返回对象/索引,否则在循环完成时返回 null 或 -1。但是,正如所指出的,Map效率更高,即使您还觉得使用起来还不够舒服,也绝对值得熟悉它。