在Java中使用arraylist对象的方法

时间:2023-02-09 23:44:11
public class Book
{
private String isbn, author, area;
private int length;
public Book(String isbn, String author, String area, int length)
{
    this.isbn=isbn;
    this.author=author;
    this.area=area;
    this.length=length;
}
public boolean isLong()
{
    if (length>500)
        return true;
    else 
        return false;
}    
} 
public class BookCollection

{
 private ArrayList<Book> bookList = new ArrayList<Book>();


public BookCollection()throws IOException
{
    Scanner fileScan;
    String oneLine;
    String isbn, author, area;
    int length;

    fileScan = new Scanner (new File("books.txt"));
    while (fileScan.hasNext())
    {
        isbn=fileScan.next();
        author=fileScan.next();
        area=fileScan.next();
        length=fileScan.nextInt();
        bookList.add(new Book(isbn, author, area, length));
    }
}
 public class TestBookCollection
{

public static void main (String[] args)throws IOException
{
    BookCollection books = new BookCollection();
    System.out.println(books);


}
}

All right here is the relevant code. My project is to read a text file that has the information about these books and put them into an arraylist of book objects. My question is: how would I go about envoking the isLong() method found in class Book on an object in an arraylist? The point of the method is, if an object has >500 pages that it returns true. If not it will return false. I'm just kind of confused about the logic and I have never really worked with Arraylists before.

这里就是相关的代码。我的项目是阅读一个文本文件,其中包含有关这些书籍的信息,并将它们放入书籍对象的arraylist中。我的问题是:如何在arraylist中的对象上调用类Book中的isLong()方法?该方法的要点是,如果一个对象有> 500页,则返回true。如果不是,它将返回false。我只是对逻辑感到困惑,而且之前从未真正与Arraylists合作过。

6 个解决方案

#1


1  

You can add another method to BookCollection:

您可以向BookCollection添加另一个方法:

public void printLongBooks() {
  for (Book book : bookList) {
    if (book.isLong()) {
       well, book is long ...
    } else {
       obviously, it is short ...
 }

The above uses the so called "for each" looping style in Java that you can use to loop every array/collection; instead of the "old school" for (int i=0; i<...) counting loop.

上面使用Java中所谓的“for each”循环样式,您可以使用它来循环每个数组/集合;而不是“旧学校”(int i = 0; i <...)计数循环。

and within your main method, you simply invoke the new method:

在main方法中,您只需调用新方法:

books.printLongBooks()

And some generic hints:

还有一些通用提示:

A) isLong() can be reduced to a one-liner: return length > 500;

A)isLong()可以简化为单行:返回长度> 500;

B) reading stuff from a file is not what you directly do in the constructor. Instead, you should create a dedicated method to that, which you then might call within the constructor

B)从文件中读取内容不是您在构造函数中直接执行的操作。相反,您应该为它创建一个专用方法,然后您可以在构造函数中调用它

#2


0  

Rather than putting the logic to create book list inside a constructor, you should create a method named as getBookCollection() that returns an arraylist.

您应该创建一个名为getBookCollection()的方法来返回一个arraylist,而不是将逻辑放在构造函数中创建book列表。

public List<Book> BookCollection()throws IOException
    {

        List<Book> bookList = new ArrayList<Book>();
        //logic to create booklist

        return booklist;
    }

Once you have list of books, you can run an enhanced for loop and check for pages in each book.

获得书籍列表后,您可以运行增强的for循环并检查每本书中的页面。

for(Book book: bookList){
        if(book.isLong()){
            //logic
        } else {
            //logic
        }
    }

#3


0  

You can use a for loop to iterate through the elements of the ArrayList and call the method on each one of its objects.

您可以使用for循环遍历ArrayList的元素,并在其每个对象上调用该方法。

for(Book book : bookList){
    boolean isLong = book.isLong();
}

#4


0  

You have a List<Book>, where each index in the List contains a Book. Use the List.get(index) method to get the Object in the given List at index. For example: bookList.get(0) gets the Book at index 0. Once you have that Object, you can use it normally.

您有一个List ,其中List中的每个索引都包含一个Book。使用List.get(index)方法在索引处获取给定List中的Object。例如:bookList.get(0)在索引0处获取Book。一旦拥有该Object,就可以正常使用它。

I assume that you have some way to get the bookList inside BookCollection, and the name of a Book?

我假设您有办法在BookCollection中获取bookList,以及Book的名称?

public static void main(String[] args){
    BookCollection books = new BookCollection(); // Make a new BookCollection
    List<Book> booksInCollection = books.getBooksList(); // Get the Books inside BookCollection
    // Go through each book in booksInCollection
    for(int index = 0; index < booksInCollection.size(); index++){
        // Get the Book Object at index
        Book currentBook = booksInCollection.get(index);
        if(currentBook.isLong()){
            System.out.println(currentBook.getName() + " is long!");
        }
    }
}

#5


0  

Firstly (if you don't want to use streams etc.) you need to get object from ArrayList. You can do it by using ArrayList.get(int index) and then invoking the method or by using for each loop:

首先(如果您不想使用流等),您需要从ArrayList获取对象。您可以使用ArrayList.get(int index)然后调用该方法或使用for each循环来完成:

for(Book book : bookList) {
    System.out.println(book.isLong());
}

The problem is that you cannot access private field (bookList) from main. There are several ways to make it work.

问题是您无法从main访问私有字段(bookList)。有几种方法可以使它工作。

  • Create a public method inside BookCollection
  • 在BookCollection中创建一个公共方法

  • Change field to public and then access it directly books.bookList
  • 将字段更改为public,然后直接访问books.bookList

  • Make a getter to your bookList in BookCollection
  • 在BookCollection中为bookList做一个getter

  • Make BookCollection extends ArrayList
  • 使BookCollection扩展ArrayList

#6


0  

What you've done here is created a decorator (BookCollection) which wraps an ArrayList with additional functionality (in this case, a constructor which pre-fills it based on a file). This gives you two options for how to make use of a Book in the List:

你在这里所做的是创建一个装饰器(BookCollection),它包含一个具有附加功能的ArrayList(在这种情况下,是一个基于文件预填充它的构造函数)。这为您提供了两种如何在列表中使用Book的选项:

  1. Make the List accessible via a getter, and then work it out. Makes statements long but this is acceptable for small amounts of usage:

    通过getter使列表可访问,然后进行处理。使语句很长,但这对于少量使用是可以接受的:

    if(books.getBooks().get(index).isLong()) {
        //The book at index is long
    }
    
  2. More commonly, you'll make methods in the decorator which offer common functionality, like so:

    更常见的是,您将在装饰器中创建提供常用功能的方法,如下所示:

    public boolean isLong(int index) {
        return bookList.get(index).isLong();
    }
    

    Then you just call the decorator method from your business logic. You can even make more complex methods such as the one offered by GhostCat.

    然后,您只需从业务逻辑中调用装饰器方法。您甚至可以制作更复杂的方法,例如GhostCat提供的方法。

#1


1  

You can add another method to BookCollection:

您可以向BookCollection添加另一个方法:

public void printLongBooks() {
  for (Book book : bookList) {
    if (book.isLong()) {
       well, book is long ...
    } else {
       obviously, it is short ...
 }

The above uses the so called "for each" looping style in Java that you can use to loop every array/collection; instead of the "old school" for (int i=0; i<...) counting loop.

上面使用Java中所谓的“for each”循环样式,您可以使用它来循环每个数组/集合;而不是“旧学校”(int i = 0; i <...)计数循环。

and within your main method, you simply invoke the new method:

在main方法中,您只需调用新方法:

books.printLongBooks()

And some generic hints:

还有一些通用提示:

A) isLong() can be reduced to a one-liner: return length > 500;

A)isLong()可以简化为单行:返回长度> 500;

B) reading stuff from a file is not what you directly do in the constructor. Instead, you should create a dedicated method to that, which you then might call within the constructor

B)从文件中读取内容不是您在构造函数中直接执行的操作。相反,您应该为它创建一个专用方法,然后您可以在构造函数中调用它

#2


0  

Rather than putting the logic to create book list inside a constructor, you should create a method named as getBookCollection() that returns an arraylist.

您应该创建一个名为getBookCollection()的方法来返回一个arraylist,而不是将逻辑放在构造函数中创建book列表。

public List<Book> BookCollection()throws IOException
    {

        List<Book> bookList = new ArrayList<Book>();
        //logic to create booklist

        return booklist;
    }

Once you have list of books, you can run an enhanced for loop and check for pages in each book.

获得书籍列表后,您可以运行增强的for循环并检查每本书中的页面。

for(Book book: bookList){
        if(book.isLong()){
            //logic
        } else {
            //logic
        }
    }

#3


0  

You can use a for loop to iterate through the elements of the ArrayList and call the method on each one of its objects.

您可以使用for循环遍历ArrayList的元素,并在其每个对象上调用该方法。

for(Book book : bookList){
    boolean isLong = book.isLong();
}

#4


0  

You have a List<Book>, where each index in the List contains a Book. Use the List.get(index) method to get the Object in the given List at index. For example: bookList.get(0) gets the Book at index 0. Once you have that Object, you can use it normally.

您有一个List ,其中List中的每个索引都包含一个Book。使用List.get(index)方法在索引处获取给定List中的Object。例如:bookList.get(0)在索引0处获取Book。一旦拥有该Object,就可以正常使用它。

I assume that you have some way to get the bookList inside BookCollection, and the name of a Book?

我假设您有办法在BookCollection中获取bookList,以及Book的名称?

public static void main(String[] args){
    BookCollection books = new BookCollection(); // Make a new BookCollection
    List<Book> booksInCollection = books.getBooksList(); // Get the Books inside BookCollection
    // Go through each book in booksInCollection
    for(int index = 0; index < booksInCollection.size(); index++){
        // Get the Book Object at index
        Book currentBook = booksInCollection.get(index);
        if(currentBook.isLong()){
            System.out.println(currentBook.getName() + " is long!");
        }
    }
}

#5


0  

Firstly (if you don't want to use streams etc.) you need to get object from ArrayList. You can do it by using ArrayList.get(int index) and then invoking the method or by using for each loop:

首先(如果您不想使用流等),您需要从ArrayList获取对象。您可以使用ArrayList.get(int index)然后调用该方法或使用for each循环来完成:

for(Book book : bookList) {
    System.out.println(book.isLong());
}

The problem is that you cannot access private field (bookList) from main. There are several ways to make it work.

问题是您无法从main访问私有字段(bookList)。有几种方法可以使它工作。

  • Create a public method inside BookCollection
  • 在BookCollection中创建一个公共方法

  • Change field to public and then access it directly books.bookList
  • 将字段更改为public,然后直接访问books.bookList

  • Make a getter to your bookList in BookCollection
  • 在BookCollection中为bookList做一个getter

  • Make BookCollection extends ArrayList
  • 使BookCollection扩展ArrayList

#6


0  

What you've done here is created a decorator (BookCollection) which wraps an ArrayList with additional functionality (in this case, a constructor which pre-fills it based on a file). This gives you two options for how to make use of a Book in the List:

你在这里所做的是创建一个装饰器(BookCollection),它包含一个具有附加功能的ArrayList(在这种情况下,是一个基于文件预填充它的构造函数)。这为您提供了两种如何在列表中使用Book的选项:

  1. Make the List accessible via a getter, and then work it out. Makes statements long but this is acceptable for small amounts of usage:

    通过getter使列表可访问,然后进行处理。使语句很长,但这对于少量使用是可以接受的:

    if(books.getBooks().get(index).isLong()) {
        //The book at index is long
    }
    
  2. More commonly, you'll make methods in the decorator which offer common functionality, like so:

    更常见的是,您将在装饰器中创建提供常用功能的方法,如下所示:

    public boolean isLong(int index) {
        return bookList.get(index).isLong();
    }
    

    Then you just call the decorator method from your business logic. You can even make more complex methods such as the one offered by GhostCat.

    然后,您只需从业务逻辑中调用装饰器方法。您甚至可以制作更复杂的方法,例如GhostCat提供的方法。