使用ArrayList类保存饭店信息,创建三个饭店的对象保存到ArrayList中,然后遍历该list并输出饭店信息;当一个饭店从ArrayList中删除后,重新输出剩下的饭店集合
时间: 2024-02-13 16:00:52 浏览: 32
好的,下面是示例代码:
```java
import java.util.ArrayList;
public class Restaurant {
private String name;
private String address;
private String phone;
public Restaurant(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
public String toString() {
return "饭店名称:" + name + ",地址:" + address + ",电话:" + phone;
}
}
public class RestaurantList {
private ArrayList<Restaurant> restaurants;
public RestaurantList() {
restaurants = new ArrayList<>();
}
public void addRestaurant(Restaurant restaurant) {
restaurants.add(restaurant);
}
public ArrayList<Restaurant> getRestaurants() {
return restaurants;
}
public void removeRestaurant(Restaurant restaurant) {
restaurants.remove(restaurant);
}
}
public class Main {
public static void main(String[] args) {
RestaurantList restaurantList = new RestaurantList();
// 创建三个饭店对象并保存到ArrayList中
Restaurant restaurant1 = new Restaurant("饭店1", "地址1", "电话1");
Restaurant restaurant2 = new Restaurant("饭店2", "地址2", "电话2");
Restaurant restaurant3 = new Restaurant("饭店3", "地址3", "电话3");
restaurantList.addRestaurant(restaurant1);
restaurantList.addRestaurant(restaurant2);
restaurantList.addRestaurant(restaurant3);
// 遍历list并输出饭店信息
System.out.println("饭店信息如下:");
for (Restaurant restaurant : restaurantList.getRestaurants()) {
System.out.println(restaurant);
}
// 删除一个饭店并输出剩下的饭店信息
restaurantList.removeRestaurant(restaurant2);
System.out.println("删除一个饭店后,剩余饭店信息如下:");
for (Restaurant restaurant : restaurantList.getRestaurants()) {
System.out.println(restaurant);
}
}
}
```
在这个示例中,我们创建了Restaurant类来表示饭店对象,RestaurantList类来表示饭店列表对象,使用ArrayList保存多个饭店对象。我们先创建了三个饭店对象并保存到ArrayList中,然后遍历该list并输出饭店信息。接着,我们删除了一个饭店对象并重新输出剩余的饭店信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)