java arraylist 参数_将ArrayList集合作为参数进行初始化类对象

用集合做参数:先在main方法中,创建book对象,放进接口之后,接口作为参数进行传递,对person对象进行初始化.

Book类:

package com.qf.demo4;

public class Book {

private String bookName;

private double price;

private String author;

public Book(String bookName, double price, String author) {

super();

this.bookName = bookName;

this.price = price;

this.author = author;

}

public Book() {

super();

}

public String getBookName() {

return bookName;

}

public void setBookName(String bookName) {

this.bookName = bookName;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public String getAuthor() {

return author;

}

public void setAuthor(String author) {

this.author = author;

}

@Override

public String toString() {

return "Book [bookName=" + bookName + ", price=" + price + ", author=" + author + "]";

}

}

Person类

注意:类的属性定义为接口,如何初始化person对象的.

package com.qf.demo4;

import java.util.ArrayList;

public class Person {

private String name;

private int age;

private ArrayList books;

public Person(String name, int age, ArrayList books) {

super();

this.name = name;

this.age = age;

this.books = books;

}

public Person() {

super();

}

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;

}

public ArrayList getBooks() {

return books;

}

public void setBooks(ArrayList books) {

this.books = books;

}

@Override

public String toString() {

return "Person [name=" + name + ", age=" + age + ", books=" + books + "]";

}

}

main方法:

package com.qf.demo4;

/**

* 集合 本身也是一个对象

* 可以作为 属性 参数 实际参数 传递

* debug

* 1 先确定要 检测的部分, 添加断点

* 2 用debug模式进行 运行

*

* Ctrl + shif + i 得到选中的语句的 结果

*

* F5 进入指定的方法

* F6 下一行

* F8 下一个断点

*/

import java.util.ArrayList;

public class Test {

public static void main(String[] args) {

ArrayList books = new ArrayList<>();

books.add(new Book("java编程思想", 108, "二狗"));

books.add(new Book("java从入门到放弃", 1008, "康帅傅"));

Person person =new Person("小香菇", 18, books);

System.out.println(person);

Person person2 = new Person();

System.out.println(person2);

person2.setName("皮皮虾");

person2.setAge(18);

System.out.println(person2);

// 必须 给 books 集合 初始化

person2.setBooks(books);

String author = person2.getBooks().get(0).getAuthor();

System.out.println(author);

int w = 5;

int i = w+7+w+4+7;

}

public static void test(){

System.out.println("abc");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值