Getter-Setter方法和数组列表

时间:2016-04-07 21:32:18

标签: java arraylist get set

我有一个类NewClass2和一个带main方法的类。基本上我想要的是我想在ArrayList中保存书名,发布日期,页数和isbn数,然后打印信息。

public class NewClass2 {
    int pages;
    String released;
    String title;
    int isbn;



    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public String getReleased() {
        return released;
    }

    public void setReleased(String released) {
        this.released = released;
    }

    public String getTitle() {
        return title;
    }

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

    public int getIsbn() {
        return isbn;
    }

    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }

    public NewClass2(int pages, String released, String title, int isbn) {
        this.pages = pages;
        this.released = released;
        this.title = title;
        this.isbn = isbn;
    }

    public NewClass2() {
    }

    public void printInfo(){
        System.out.println("The book has "+pages+" pages and was released on "+released+" and is called "+title);
    }

}

主要课程:

    public class mainClass {
    public static void main(String[] args){
        ArrayList<NewClass2> listTest = new ArrayList<>( );
        listTest.add(new NewClass2( 200,"Book 1", "8.9.14",2222) );
        listTest.add(new NewClass2( 200,"Book 2", "1.2.04",5555) );
        listTest.add(new NewClass2( 200,"Book 3", "5.4.06",6666) );
        listTest.add(new NewClass2( 200,"Book 4", "7.4.13",7777) );
        listTest.add(new NewClass2( 200,"Book 5", "2.2.03",8888) );

        NewClass2 book = new NewClass2(listTest);

        book.printInfo();

    }
}

IDE告诉我

NewClass2 book = new NewClass2(listTest);

错了但为什么?以及如何解决它?

1 个答案:

答案 0 :(得分:2)

您的问题如下:

In&#34; NewClass2&#34;你有

  1. int页面的构造函数,String release,String title和int isbn
  2. (){nothing}
  3. 的构造函数

    要获取ArrayList的每本书,您可以替换以下行

    NewClass2 book = new NewClass2(listTest);
    book.printInfo();
    

    for (NewClass2 book : listTest){
        book.printInfo();
    }
    

    这将打印ArrayList中每本书的信息。

    我希望我可以帮助你。