【问题标题】:Update ArrayList, only if it equals a bookID?仅当它等于 bookID 时才更新 ArrayList?
【发布时间】: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 的新Stream API 和filter List,用于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 效率更高,即使您还觉得使用起来还不够舒服,也绝对值得熟悉它。

标签: java arraylist


【解决方案1】:

直接方法...

所有这一切都会循环通过Books 的List 并将用户输入的bookID 与书的bookID 进行比较。如果找到匹配项,则 Book 引用将保留在变量 bookToEdit 中。

如果循环完成后,bookToEditnull,那么在 List 中没有与指定 ID 匹配的 Book,否则,您现在有一个需要参考的书已编辑

// Get which part, and book the user would like to edits
System.out.print("Enter Book ID to begin editing: ");
int bookID = sc.nextInt();
sc.nextLine();
Book bookToEdit = null;
for (Book book : newBook) {
    if (book.getId() == bookID) {
        bookToEdit = book;
        break;
    }
}
if (bookToEdit != null) {

    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();
    sc.nextLine();

    if (editOption == 1 || editOption == 2) {
        System.out.print("New " + (editOption == 1 ? "title: " : "author: "));
        String value = sc.nextLine();
        switch (editOption) {
            case 1:
                // Update title
                break;
            case 2:
                // Update author
                break;
        }
    } else {
        System.out.println("Invalid edit option");
    }

} else {
    System.out.println("Book with the id of " + bookID + " does not exist");
}

Streams

如果你想做一些更花哨的事情,你可以使用...

// Get which part, and book the user would like to edits
System.out.print("Enter Book ID to begin editing: ");
int bookID = sc.nextInt();
sc.nextLine();

List<Book> filtered = newBook.stream().filter((Book t) -> t.getId() == bookID).collect(Collectors.toList());
if (!filtered.isEmpty()) {
    Book bookToEdit = filtered.get(0);

现在,您需要知道,这比上一个循环效率低,因为它将循环遍历 newBook 的整个 List 并返回与 bookId 匹配的所有书籍(有实际上应该只有一个)

Map

最有效的方法是将Books 维护在Map 中,而不是List,键入bookId。这样,在需要时,您可以简单地通过它的 id 来查找这本书

Map<Integer, Book> newBook = new HashMap<>();
//...
newBook.put(1, new Book(1, "Star Wars", "Somebody"));
newBook.put(2, new Book(2, "Harry Potter", "Somebody else"));
//...

// Get which part, and book the user would like to edits
System.out.print("Enter Book ID to begin editing: ");
int bookID = sc.nextInt();
sc.nextLine();

if (newBook.containsKey(bookID)) {
    Book bookToEdit = newBook.get(bookID);

从概念上讲,所有这些都是在键和对象之间生成映射或关系,这使得根据提供的键查找对象变得更快、更简单

查看Collections Trail了解更多详情

【讨论】:

    【解决方案2】:

    请使用地图来解决您的问题。 您可以访问: http://www.tutorialspoint.com/java/java_map_interface.htm.

    以下是为您提供的一些示例代码:

        //init the map
        Map<String, Book> dataMap = Maps.newHashMap();
    
    
        //insert record
        dataMap.put(bookId, book);
    
    
        //update record
        Optional<Book> bookOpt = Optional.ofNullable(dataMap.get(bookId));
        bookOpt.ifPresent(book->{
            book.setTitle(newTitle);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 2021-08-16
      • 1970-01-01
      相关资源
      最近更新 更多