Java中如何将其他类的对象存储到不同类的ArrayList中
问题背景
当前项目三个类的设计目标:
Countries类:定义国家实体,包含国家名称、国际电话区号两个核心属性CountriesList类:通过ArrayList存储所有Countries类的实例person类:接收用户输入的国家名称、手机号码,匹配已存储的国家数据,输出对应电话区号
当前故障:无法将Countries类的实例存入CountriesList类的ArrayList中,多次调整代码均报错。
故障原因
- 成员变量类型声明错误:
CountriesList中声明的private Countries list;是单个Countries类型的变量,无法存储多个对象,不符合集合存储的需求。 - 变量作用域混淆:
CountriesList构造方法内写的ArrayList<Countries> list = new ArrayList<>();是构造方法的局部变量,和类成员变量没有关联,构造方法执行结束后该局部变量会被直接回收,外部无法访问,自然无法存入数据。 - 缺少必要逻辑:没有对外提供集合操作的公共方法,也没有导入
ArrayList对应的依赖包;之前在Countries类main方法中创建的国家实例都是该方法的局部变量,没有主动传入集合,集合始终为空。
修正后可运行代码
1. Countries实体类
去掉类中不必要的main方法,保持实体类的单一职责:
public class Countries { private String countryname; private int phonecode; public Countries(String n, int c){ this.countryname = n; this.phonecode = c; } public String getCountryName(){ return this.countryname; } public int getPhoneCode(){ return this.phonecode; } }
2. CountriesList集合管理类
修正成员变量类型,初始化集合,预置国家数据,对外提供添加、查询方法:
import java.util.ArrayList; public class CountriesList { // 声明正确的集合类型成员变量 private ArrayList<Countries> countryList; public CountriesList(){ // 直接初始化成员变量,不要创建同名局部变量 countryList = new ArrayList<>(); // 预置国家数据直接存入集合 countryList.add(new Countries("USA",1)); countryList.add(new Countries("India",91)); countryList.add(new Countries("Afg",677)); countryList.add(new Countries("Bangladesh",880)); countryList.add(new Countries("UK",44)); } // 对外提供添加国家实例的方法 public void addCountry(Countries country){ countryList.add(country); } // 对外提供根据国家名查询区号的方法,供person类调用 public int getPhoneCodeByCountryName(String countryName){ for (Countries country : countryList) { // 字符串内容比较用equals方法,忽略大小写适配用户输入 if(country.getCountryName().equalsIgnoreCase(countryName)){ return country.getPhoneCode(); } } // 找不到对应国家返回-1作为错误标识 return -1; } }
3. person交互类
实现用户输入接收、匹配查询、结果输出逻辑:
import java.util.Scanner; public class person { public static void main(String[] args) { CountriesList countriesList = new CountriesList(); Scanner sc = new Scanner(System.in); System.out.println("请输入国家名称:"); String inputCountry = sc.nextLine(); System.out.println("请输入手机号码:"); String inputPhone = sc.nextLine(); int code = countriesList.getPhoneCodeByCountryName(inputCountry); if(code == -1){ System.out.println("未查询到对应国家的电话区号"); }else{ System.out.printf("对应国际电话区号为:+%d,完整号码为:+%d%s%n", code, code, inputPhone); } sc.close(); } }
编码注意点
- 类成员变量和方法内局部变量是完全独立的,不要在方法内声明和成员变量同名的局部变量,会导致成员变量无法被正确赋值。
- 存储多个同类型对象时,成员变量类型要声明为对应的集合类型,不要用单个实体类型声明。
- Java中字符串内容比较要用
equals()/equalsIgnoreCase()方法,不要直接用==,后者比较的是对象内存地址,不是实际内容。
内容的提问来源于stack exchange,提问作者Zac3244
相关产品推荐
相关产品推荐

