【笔记】Eclipse and Java for Total Beginners—009

Lesson 09 – MyLibrary Class and ArrayList

  • How can we hold books, etc. in a collection?
  • MyLibrary object to hold Person & Entry objects
  • Introduce ArrayList in scrapbook
  • Introduce Java Generics
  • Method chaining

使用ArrayList前,要添加java.util.

1 ArrayList<Book> list = new ArrayList<Book>();
2
3 Book b1 = new Book("Great Expectations");
4 Book b2 = new Book("War and Peace");
5 list.add(b1);
6 list.add(b2);
7
8 Person p1 = new Person();
9 p1.setName("Fred");
10 b1.setPerson(p1);
11
12 list.get(0).getPerson().getName();
13
14 list.remmove(b1);
15 list

问题:Inspect提示:

Book cannot be resolved to a type
Book cannot be resolved to a type
Book cannot be resolved to a type
Book cannot be resolved to a type
Book cannot be resolved to a type
Book cannot be resolved to a type

问题解决方法:

1> 在编辑代码时输入new后,按ALT+/ 自动补齐,无反应。

     windows / preferences / Java / Editor / Templates / 选new / Edit / 勾选 Automatically insert / 在context里选 Java。

2>Book cannot be resolved to a type,添加Book

    1) Click the "Set Import Declarations" button right next to red square "Stop evaluation" button.

    2) Select "org.totalbeginner.tutorial* "-> click the "Add Type" button  

    3) Search for class 'Book' and 'Person' and add them to your MyScrapbook.jpage

小结:

  在上面的代码里,用ArrayList列出了Library Class的特性,用Scrapbook验证时,可灵活调用各种方法,比如,根据Book对象去查询:

      list.indexOf(b2);

     或是由书查读者:

      list.get(0).getPerson().getName();

原文地址:https://www.cnblogs.com/halflife/p/2078558.html