集合框架-ArrayList集合存储自定义对象
2021/10/19 23:09:58
本文主要是介绍集合框架-ArrayList集合存储自定义对象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1 package cn.itcast.p3.arraylist.test; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 import com.sun.org.apache.bcel.internal.generic.NEW; 7 8 import cn.itcast.p.bean.Person; 9 import sun.jvm.hotspot.ui.action.ShowAction; 10 11 public class ArrayListTest { 12 13 public static void main(String[] args) { 14 // TODO Auto-generated method stub 15 ArrayList al = new ArrayList(); 16 al.add(new Person("list1",21)); 17 al.add(new Person("list2",22)); 18 al.add(new Person("list3",23)); 19 al.add(new Person("list4",24)); 20 21 22 Iterator it = al.iterator(); 23 while (it.hasNext()) { 24 //System.out.println(((Person)it.next()).getName()+"::"+((Person) it.next()).getAge()); 25 //list1::22 26 //list2::24 会多次调用it.next()会出错 27 Person person = (Person)it.next(); 28 System.out.println(person.getName()+"::"+person.getAge()); 29 } 30 31 al.add(5);//al.add(new Integer(5)) ,jdk1.5以后可以直接用因为自动装箱 32 show(6); 33 } 34 35 private static void show(Integer num) {//Object num = 6 //new Integer(6) 只要觉得类型符合就装箱,当基本数据类型给引用数据类型时就是装箱 36 // TODO Auto-generated method stub 37 int x = num + 8;//当引用数据类型和基本数据类型作运算 拆箱 38 } 39 40 }View Code
1 package cn.itcast.p.bean; 2 3 public class Person { 4 private String name; 5 private int age; 6 7 8 public Person() { 9 super(); 10 // TODO Auto-generated constructor stub 11 } 12 public Person(String name, int age) { 13 super(); 14 this.name = name; 15 this.age = age; 16 } 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 public int getAge() { 24 return age; 25 } 26 public void setAge(int age) { 27 this.age = age; 28 } 29 //ctrl+alt+s 快捷构造set,get方法 初始化等 30 }View Code
这篇关于集合框架-ArrayList集合存储自定义对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南