如何在Main类中获取Father类List<Vehicle>的车辆品牌?
解决Java中打印Vehicle对象显示[Vehicle@xxxx]的问题并实现需求
问题原因
直接打印father.getVehicles()时输出[Vehicle@15db9742],是因为:
- Java打印集合时,会自动调用集合内每个元素的
toString()方法 Vehicle类未重写Object类的默认toString()方法,默认实现会输出类名@对象哈希码的格式
实现需求的两种方案
方案1:重写Vehicle类的toString()方法
通过重写toString(),让打印Vehicle对象时直接显示品牌信息,同时完成所有需求:
修改后的Vehicle类:
public class Vehicle { String brand; String type; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getType() { return type; } public void setType(String type) { this.type = type; } // 重写toString,返回品牌信息 @Override public String toString() { return "品牌:" + brand; } }
修改后的Main类(完成所有需求):
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Vehicle> vehicleList = new ArrayList<>(); Vehicle vehicle = new Vehicle(); vehicle.setBrand("Toyota"); vehicleList.add(vehicle); Father father = new Father(); father.setVehicles(vehicleList); // 打印Father的所有车辆品牌 System.out.println("Father的车辆品牌:"); System.out.println(father.getVehicles()); // 添加新的车辆品牌 Vehicle newVehicle = new Vehicle(); newVehicle.setBrand("Honda"); father.getVehicles().add(newVehicle); // 打印最后一个车辆品牌 List<Vehicle> vehicles = father.getVehicles(); if (!vehicles.isEmpty()) { System.out.println("Father拥有的最后一个车辆品牌:" + vehicles.get(vehicles.size() - 1)); } } }
方案2:遍历集合手动获取品牌(无需修改Vehicle类)
如果不想修改Vehicle类,可以直接遍历List,调用getBrand()方法获取品牌信息:
修改后的Main类:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Vehicle> vehicleList = new ArrayList<>(); Vehicle vehicle = new Vehicle(); vehicle.setBrand("Toyota"); vehicleList.add(vehicle); Father father = new Father(); father.setVehicles(vehicleList); // 打印Father的所有车辆品牌 System.out.println("Father的车辆品牌:"); for (Vehicle v : father.getVehicles()) { System.out.println(v.getBrand()); } // 添加新的车辆品牌 Vehicle newVehicle = new Vehicle(); newVehicle.setBrand("Honda"); father.getVehicles().add(newVehicle); // 打印最后一个车辆品牌 List<Vehicle> vehicles = father.getVehicles(); if (!vehicles.isEmpty()) { Vehicle lastVehicle = vehicles.get(vehicles.size() - 1); System.out.println("Father拥有的最后一个车辆品牌:" + lastVehicle.getBrand()); } } }
输出结果
两种方案最终都会输出:
Father的车辆品牌: Toyota Father拥有的最后一个车辆品牌:Honda
内容的提问来源于stack exchange,提问作者Ariff Haikal
相关产品推荐
相关产品推荐

