创建一个Arraylist,然后向里面添加一个Loan对象,并用toString()显示列表中的元素
时间: 2024-01-28 11:05:41 浏览: 64
如何向WebServices中传送多个自定义类对象
5星 · 资源好评率100%
好的,以下是用Java语言实现的代码:
首先需要定义一个Loan类,代码如下:
```java
public class Loan {
private String borrower;
private double amount;
public Loan(String borrower, double amount) {
this.borrower = borrower;
this.amount = amount;
}
public String getBorrower() {
return borrower;
}
public void setBorrower(String borrower) {
this.borrower = borrower;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
@Override
public String toString() {
return "Loan{" +
"borrower='" + borrower + '\'' +
", amount=" + amount +
'}';
}
}
```
然后创建一个ArrayList对象,往里面添加Loan对象,并用toString()方法显示列表中的元素:
```java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Loan> loanList = new ArrayList<>();
loanList.add(new Loan("Alice", 1000.0));
loanList.add(new Loan("Bob", 2000.0));
loanList.add(new Loan("Charlie", 3000.0));
for (Loan loan : loanList) {
System.out.println(loan.toString());
}
}
}
```
输出结果为:
```
Loan{borrower='Alice', amount=1000.0}
Loan{borrower='Bob', amount=2000.0}
Loan{borrower='Charlie', amount=3000.0}
```
希望能够帮到您!
阅读全文