一:创建一个学生的类
package cn.tx.Array;
import java.util.ArrayList;
import java.util.Collection;
public class Student {
private Integer stuNo;
private String name;
private int age;
//在学生类中添加一个book(书)集合属性
private Collection books = new ArrayList();
public Student(Integer stuNo, String name, int age) {
this.stuNo = stuNo;
this.name = name;
this.age = age;
}
//学生的books的对外方法也叫封装
public Collection getBooks() {
return books;
}
public void setBooks(Collection books) {
this.books = books;
}
public Integer getStuNo() {
return stuNo;
}
public void setStuNo(Integer stuNo) {
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//把book加进去
@Override
public String toString() {
return “Student{” +
“stuNo=” + stuNo +
“, name=’” + name + ‘’’ +
“, age=” + age +
“, books=” + books +
‘}’;
}
}
二:创建书的类
package cn.tx.coll;
public class book {
private String name;//书的名字
private double price;//价格
public book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "book{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
三:
package cn.tx.coll;
//集合的扩展练习2
import cn.tx.Array.Student;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
public class CollectionDemo2 {
public static void main(String[] args) {
//创建一个集合Collection
Collection c = new ArrayList();
//创建一个学生对象
Student s = new Student(1, “王磊”, 20);
//获得这个学生的对象的集合,添加书籍
Collection books = s.getBooks();
//添加书的属性
books.add(new book(“历史”,25.8));
Student s1 = new Student(2, "罗平", 18);
Collection books1 = s1.getBooks();
//添加书的属性
books1.add(new book("语文",22.3));
c.add(s);
c.add(s1);
System.out.println(c);
}
}
四:打印
[Student{stuNo=1, name=‘王磊’, age=20, books=[book{name=‘历史’, price=25.8}]}, Student{stuNo=2, name=‘罗平’, age=18, books=[book{name=‘语文’, price=22.3}]}]
Process finished with exit code 0