如何将String类型ArrayList转为Phone对象ArrayList解决类型不兼容错误
Java类型不兼容问题修复方案
问题核心
- 你定义的
getCurrentRun()方法返回值为ArrayList<String>,但不可修改的调用代码要求接收ArrayList<Phone>,二者类型不匹配是报错的直接原因 - 原有循环逻辑存在数组越界风险:循环上限写为
counter+1,但Phones列表的有效索引范围是0 ~ counter-1 - 直接打印Phone对象会输出内存地址,需要重写
toString()方法才能输出属性内容
修复代码
第一步:修改getCurrentRun()方法返回值
直接返回Phone对象的集合,不需要提前拼接为字符串:
// 把返回类型从ArrayList<String>改成ArrayList<Phone> public static ArrayList<Phone> getCurrentRun() { // 直接返回Phones列表的副本,避免外部修改静态列表内容 return new ArrayList<>(Phones); }
第二步:在Phone类中添加toString()方法
@Override public String toString() { return Brand + " " + Type + " " + Model + " " + UniqueID + " " + ManufCost; }
第三步:修复原有逻辑漏洞(可选)
你可以删除冗余的counter静态变量,直接调用Phones.size()就能获取已创建的Phone实例数量,避免计数和列表长度不一致的问题。
完整修正后Phone类代码
import java.util.ArrayList; public class Phone { private String Brand; private String Type; private String Model; private String UniqueID; private int ManufCost; public static ArrayList<Phone> Phones = new ArrayList<Phone>(); public Phone(String Brand, String Type, String Model, String UniqueID, int ManufCost) { this.Brand=Brand; this.Type=Type; this.Model=Model; this.UniqueID=UniqueID; this.ManufCost=ManufCost; Phones.add(this); } public static ArrayList<Phone> getCurrentRun() { return new ArrayList<>(Phones); } @Override public String toString() { return Brand + " " + Type + " " + Model + " " + UniqueID + " " + ManufCost; } }
修改后无需调整你不能修改的调用代码,运行即可正常打印出所有Phone对象的属性信息。
内容的提问来源于stack exchange,提问作者SomeRandomName
相关产品推荐
相关产品推荐

