如何利用toString与增强for循环优化ContactArrayList的信息展示
嘿,这个需求其实很容易优雅地实现,咱们一步步来搞定它:
第一步:给Contact类重写toString()方法
要让联系人信息展示得友好,首先得让每个Contact对象自己知道怎么输出有意义的内容——这就得重写Object类的toString()方法,不然默认会打印对象的哈希值,完全没用。
举个例子,假设你的Contact类有姓名、电话属性,重写后应该是这样:
public class Contact { private String name; private String phone; // 构造方法、getter/setter这些就不啰嗦了 @Override public String toString() { return String.format("【联系人】姓名:%s | 电话:%s", name, phone); // 要是有其他属性(比如邮箱、地址),直接加进去就行 } }
第二步:让ContactArrayList支持增强for循环
增强for循环(foreach)需要遍历的对象实现Iterable接口,所以咱们得给自定义的ContactArrayList加上这个实现,这样外部代码就能直接用foreach遍历,不用关心内部怎么存储的。
假设你的ContactArrayList内部是用ArrayList<Contact>来维护数据的,修改后代码大概是这样:
import java.util.ArrayList; import java.util.Iterator; public class ContactArrayList implements Iterable<Contact> { private ArrayList<Contact> internalList; public ContactArrayList() { internalList = new ArrayList<>(); } // 你已经有的add、remove、size、isEmpty方法 public void add(Contact contact) { internalList.add(contact); } // 实现Iterable接口的核心方法,返回迭代器 @Override public Iterator<Contact> iterator() { return internalList.iterator(); } // 其他自定义方法... }
要是你不想改ContactArrayList的代码,也可以给它加一个返回内部集合的方法(比如getAllContacts()),不过实现Iterable是更优雅的做法,符合封装原则。
第三步:在主类里用增强for循环展示列表
现在就简单了,在你的驱动类里,直接用foreach遍历ContactArrayList实例,每个Contact对象会自动调用咱们重写的toString()方法,输出友好的信息:
public class ContactDriver { public static void main(String[] args) { // 你已经实例化的ContactArrayList对象 ContactArrayList myContacts = new ContactArrayList(); // 假设你已经添加了若干联系人,比如user、ca1、ca2... myContacts.add(new Contact("user", "13500001111")); myContacts.add(new Contact("ca01", "13600002222")); myContacts.add(new Contact("ca02", "13700003333")); // 展示联系人列表 System.out.println("===== 我的联系人列表 ====="); for (Contact contact : myContacts) { System.out.println(contact); // 等价于System.out.println(contact.toString()); } } }
为啥这是更优的方式?
- 可读性拉满:增强for循环比传统的索引循环简洁太多,一眼就能看明白是在遍历所有联系人。
- 代码复用:
toString()方法写一次,不管在哪打印Contact对象都能输出一致的格式,不用每次手动拼接属性。 - 符合封装:实现
Iterable后,外部代码不需要知道ContactArrayList内部是用什么存数据的,就算以后换成LinkedList,遍历代码也不用改。
内容的提问来源于stack exchange,提问作者EOxJ
相关产品推荐
相关产品推荐

