简体   繁体   English

ArrayList重用单个对象,而不是创建新的对象

[英]ArrayList re-using single Object, instead of creating new ones

I am working on a simple program that reads a text file that contains book titles and the associated reference number. 我正在研究一个简单的程序,该程序读取包含书名和相关参考号的文本文件。 Each set of information should be turned into a Book object so that it can be sorted later on. 每组信息都应转换为Book对象,以便以后进行排序。 However, in the current code, whenever a new Book should be created, it re-uses the original Book. 但是,在当前代码中,每当应创建新Book时,它都会重新使用原始Book。 I have added a counter to the Book class to track the amount of Book objects. 我在Book类中添加了一个计数器来跟踪Book对象的数量。

The program should create a new Book object using the book title and associated reference number. 该程序应使用书名和关联的参考号创建一个新的Book对象。 What would I change/add in order to fix this problem? 为了解决此问题,我将进行哪些更改/添加?

Main Class 主班

    private static ArrayList<Book> books = new ArrayList();

    public static void main(String[] args) {
        String path = "src//booklist.txt";
        boolean endOfFile = false;

        // try/catch for reading the file
        try {
            FileReader fr = new FileReader(path);
            BufferedReader br = new BufferedReader(fr);

            while (!endOfFile) {
                String line = br.readLine();

                if (line == null) {
                    endOfFile = true;
                } else {
                    books.add(new Book(null, 0));
                    books.get(books.size() - 1).setRefNum(Integer.parseInt(line));

                    String bookTitle = br.readLine();
                    books.get(books.size() - 1).setTitle(bookTitle);
                }
                System.out.println(books.get(books.size() - 1).toString());
            }
            // Closing reader and displaying results
            br.close();
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }
}

Book Class 书类

private String bookTitle;
private int refNum;
private int numBooks;

public Book(String title, int referenceNumber) {
    this.bookTitle = title;
    this.refNum = referenceNumber;
    this.numBooks++;
}

public String getTitle() {
    return this.bookTitle;
}

public void setTitle(String title) {
    this.bookTitle = title;
}

public int getRefNum() {
    return this.refNum;
}

public void setRefNum(int referenceNumber) {
    this.refNum = referenceNumber;
}

public int getNumBooks() {
    return this.numBooks;
}

public String toString() {
    String message = "Book Title: " + this.bookTitle
            + "\nReference #: " + this.refNum
            + "\nBook #: " + this.numBooks
            + "\n";
    return message;
}

Text Document ( booktitles.txt ) 文字文件booktitles.txt

1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
10
Treasure Island
12
The Secret Garden
14
Alice's Adventures in Wonderland
20
Twenty Thousand Leagues Under the Sea
24
Peter Pan
26
Charlotte's Web
31
A Little Princess
32
Little Women
33
Black Beauty
35
The Merry Adventures of Robin Hood
40
Robinson Crusoe
46
Anne of Green Gables
50
Little House in the Big Woods
52
Swiss Family Robinson
54
The Lion, the Witch and the Wardrobe
56
Heidi
66
A Winkle in Time
100
Mary Poppins

Current Output 电流输出

Book Title: The Adventures of Tom Sawyer
Reference #: 1
Book #: 1

Book Title: Huckleberry Finn
Reference #: 2
Book #: 1

Book Title: The Sword in the Stone
Reference #: 4
Book #: 1

Book Title: Stuart Little
Reference #: 6
Book #: 1

Book Title: Treasure Island
Reference #: 10
Book #: 1

Book Title: The Secret Garden
Reference #: 12
Book #: 1

Book Title: Alice's Adventures in Wonderland
Reference #: 14
Book #: 1

Book Title: Twenty Thousand Leagues Under the Sea
Reference #: 20
Book #: 1

Book Title: Peter Pan
Reference #: 24
Book #: 1

Book Title: Charlotte's Web
Reference #: 26
Book #: 1

Book Title: A Little Princess
Reference #: 31
Book #: 1

Book Title: Little Women
Reference #: 32
Book #: 1

Book Title: Black Beauty
Reference #: 33
Book #: 1

Book Title: The Merry Adventures of Robin Hood
Reference #: 35
Book #: 1

Book Title: Robinson Crusoe
Reference #: 40
Book #: 1

Book Title: Anne of Green Gables
Reference #: 46
Book #: 1

Book Title: Little House in the Big Woods
Reference #: 50
Book #: 1

Book Title: Swiss Family Robinson
Reference #: 52
Book #: 1

Book Title: The Lion, the Witch and the Wardrobe
Reference #: 54
Book #: 1

Book Title: Heidi
Reference #: 56
Book #: 1

Book Title: A Winkle in Time
Reference #: 66
Book #: 1

Book Title: Mary Poppins
Reference #: 100
Book #: 1

Desired Output 期望的输出

Book Title: The Adventures of Tom Sawyer
Reference #: 1
Book #: 1

Book Title: Huckleberry Finn
Reference #: 2
Book #: 2

Book Title: The Sword in the Stone
Reference #: 4
Book #: 3

Book Title: Stuart Little
Reference #: 6
Book #: 4

Book Title: Treasure Island
Reference #: 10
Book #: 5

Book Title: The Secret Garden
Reference #: 12
Book #: 6

Book Title: Alice's Adventures in Wonderland
Reference #: 14
Book #: 7

Book Title: Twenty Thousand Leagues Under the Sea
Reference #: 20
Book #: 8

Book Title: Peter Pan
Reference #: 24
Book #: 9

Book Title: Charlotte's Web
Reference #: 26
Book #: 10

Book Title: A Little Princess
Reference #: 31
Book #: 11

Book Title: Little Women
Reference #: 32
Book #: 12

Book Title: Black Beauty
Reference #: 33
Book #: 13

Book Title: The Merry Adventures of Robin Hood
Reference #: 35
Book #: 14

Book Title: Robinson Crusoe
Reference #: 40
Book #: 15

Book Title: Anne of Green Gables
Reference #: 46
Book #: 16

Book Title: Little House in the Big Woods
Reference #: 50
Book #: 17

Book Title: Swiss Family Robinson
Reference #: 52
Book #: 18

Book Title: The Lion, the Witch and the Wardrobe
Reference #: 54
Book #: 19

Book Title: Heidi
Reference #: 56
Book #: 20

Book Title: A Winkle in Time
Reference #: 66
Book #: 21

Book Title: Mary Poppins
Reference #: 100
Book #: 22

I think you misunderstand the code 我认为您误解了代码

books.add(new Book(null, 0));
books.get(books.size() - 1).setRefNum(Integer.parseInt(line));
String bookTitle = br.readLine();
books.get(books.size() - 1).setTitle(bookTitle);

This is creating a new Book each time. 每次都在创建一Book However it is inefficient. 但是它效率低下。 Consider 考虑

Book b = new Book(null,0);
books.add(b);
b.setRefNum(Integer.parseInt(line));
String bookTitle = br.readLine();
b.setTitle(bookTitle);

Variable b is local to the loop. 变量b在循环本地。 Even better, use the constructor 更好的是,使用构造函数

String bookTitle = br.readLine();
Book b = new Book(bookTitle,Integer.parseInt(line));
books.add(b);

As to the clarified question: 关于澄清的问题:

numBooks is an instance variable so there's one copy for every book. numBooks是一个实例变量,因此每本书都有一个副本。 What you need is to use books.size() to retrieve the number of entries in the list. 您需要使用books.size()来检索列表中的条目数。 Remove numBooks from the Book class, it is not necessary. Book类中删除numBooks ,这是没有必要的。

use the proper values in the constructor so that a dummy book does not need to be added and subsequently got in order to be updated 在构造函数中使用适当的值,这样就无需添加dummy书,随后got可以获取dummy书以进行更新

String bookTitle = br.readLine();
books.add(new Book(bookTitle, Integer.parseInt(line)));

Replace the lines 更换线

books.add(new Book(null, 0));
books.get(books.size() -1).setRefNum(Integer.parseInt(line));

String bookTitle = br.readLine();
books.get(books.size() - 1).setTitle(bookTitle);

By 通过

String bookTitle = br.readLine();
books.add(new Book(bookTitle,Integer.parseInt(line)));

Your problem is in the Book class with numBooks.You do not need this . 您的问题出在numBooks的Book类中。您不需要此类。 You can use arrayList books and its index for the output. 您可以将arrayList书籍及其索引用于输出。

The counter added to Book class is not static. 添加到Book类的计数器不是静态的。 So it would be unique for each new instance of Book object. 因此,它对于Book对象的每个新实例都是唯一的。 So it will always be one. 因此它将永远是一个。

private int numBooks;

public Book(String title, int referenceNumber) {
    this.bookTitle = title;
    this.refNum = referenceNumber;
    this.numBooks++;
}

Do you not see multiple books added from the ArrayList books object? 您没有看到从ArrayList图书对象添加的多本书吗?

System.out.println(books.get(books.size() - 1).toString());

As per your current output, title is changing, but book# is not changing. 根据您当前的输出,标题正在更改,但是书号没有更改。

Make numBooks static. 使numBooks静态。 Static variables are linked with a class instead of being instances of the class, thus the same variable will be shared across all objects which are instance of the same class. Static变量与类链接,而不是作为类的实例,因此,相同变量将在属于同一类实例的所有对象之间共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM