java ArrayList 练习2-存储自定义

 题目:
 * 自定义4个person对象,添加到集合,并遍历
 * 
 * 思路:
 * 1.自定义Person类 ,四个部分
 * 2.创建一个集合,用来存储person对象,泛型<Person>
 * 3.g根据类,创建4个person对象
 * 5.遍历集合:for.size,get

想创建一个person类

public class Person {
	private String name;
	private int age;
	public Person() {
	}
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
 
}
public class Test08ArrayListPerson {

	public static void main(String[] args) {
		//创建一个泛型的集合
		ArrayList<Person> list=new ArrayList<>();
		//创建4个人物对象
		
		Person one=new Person("周星驰",44);
		Person two=new Person("周润发",45);
		Person three=new Person("刘德华",46);
		Person four=new Person("龙五",47);

		list.add(one);
		list.add(two);
		list.add(three);
		list.add(four);
		//遍历集合
		for (int i=0;i<list.size();i++) {
		//	System.out.println(list.get(i));//同样是打印的事地址值
		//	System.out.println(list);//地址值  上面one two three four
			//上面打数据传进去   这里我们获取数据
			Person per=list.get(i);//这里放数据放进去的是个人物,我们拿出也应是是人物
			System.out.println("姓名"+per.getName()+"  年龄"+per.getAge());
// result:姓名周星驰  年龄44
//         姓名周润发  年龄45
//	       姓名刘德华  年龄46
//	       姓名龙五   年龄47

发布了10 篇原创文章 · 获赞 0 · 访问量 84

猜你喜欢

转载自blog.csdn.net/Q791425037/article/details/105646747