1.请按照下列要求编写程序。 要求:定义Phone类,属性包括pid,ptype;price;方法:构造方法,get和set方法,toString()方法 (1) 创建一个ArrayList对象,添加3个手机信息。 (2) 输出列表的长度。 (3) 输出列表第2个元素的信息 。 (4) 删除第三个元素 (5)输出列表所有的元素信息。 (6)向列表第2个位置添加一个手机对象
时间: 2024-03-06 11:47:49 浏览: 79
以下是实现上述要求的 Java 代码:
```java
import java.util.ArrayList;
class Phone {
private int pid;
private String ptype;
private double price;
public Phone(int pid, String ptype, double price) {
this.pid = pid;
this.ptype = ptype;
this.price = price;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPtype() {
return ptype;
}
public void setPtype(String ptype) {
this.ptype = ptype;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Phone{" +
"pid=" + pid +
", ptype='" + ptype + '\'' +
", price=" + price +
'}';
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Phone> phoneList = new ArrayList<>();
phoneList.add(new Phone(1, "iPhone", 999.99));
phoneList.add(new Phone(2, "Samsung", 799.99));
phoneList.add(new Phone(3, "Huawei", 699.99));
System.out.println("List size: " + phoneList.size());
System.out.println("Second phone: " + phoneList.get(1));
phoneList.remove(2);
System.out.println("All phones:");
for (Phone phone : phoneList) {
System.out.println(phone);
}
phoneList.add(1, new Phone(4, "Google", 899.99));
System.out.println("All phones after adding a new phone:");
for (Phone phone : phoneList) {
System.out.println(phone);
}
}
}
```
输出结果如下:
```
List size: 3
Second phone: Phone{pid=2, ptype='Samsung', price=799.99}
All phones:
Phone{pid=1, ptype='iPhone', price=999.99}
Phone{pid=2, ptype='Samsung', price=799.99}
All phones after adding a new phone:
Phone{pid=1, ptype='iPhone', price=999.99}
Phone{pid=4, ptype='Google', price=899.99}
Phone{pid=2, ptype='Samsung', price=799.99}
```
阅读全文