给对象的集合属性赋值的两种方法

427 阅读1分钟
public class Student {
    private String name;
    private int age;
    private Collection books = new ArrayList();//学生的集合属性,里面可以有若干值
    
     public Student(String name, int age, Collection books) {
        this.name = name;
        this.age = age;
        this.books = books;
    }
  }    
//方法一
public class Text {
    public static void main(String[] args) {
        Student s = new Student();
        Collection b = s.getBooks();//把对象的集合属性的值用另一个集合来接收
        b.add("书剑恩仇录");
        b.add("龙族");
        b.add("安德的影子");
        System.out.println(s);
    }
    方法二:
     public static void main(String[] args) {
        Collection coll = new ArrayList();
        Student s = new Student("小明",20, Collections.singleton("书剑恩仇录,龙族,安德的影子"));
        System.out.println(sl);
    }

新手学习总结,如有错误,欢迎指正。