JAVA 集合存储自定义类型对象

集合存储自定义类型对象

集合可以存放仍和一种引用类型,包含我们自定义的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 ArrayListCustom {
	public static void main(String[] args) {
		// 首先创建几个Person对象
		Person one = new Person("AA", 18);
		Person two = new Person("BB", 19);
		Person three = new Person("CC", 20);

		// 准备一个集合,用来存放多个Person 对象
		ArrayList<Person> list = new ArrayList<>();

		// 将对象添加到集合当中
		list.add(one);
		list.add(two);
		list.add(three);

		// 遍历集合
		for (int i = 0; i < list.size(); i++) {
			Person per = list.get(i);
			System.out.println("姓名:" + per.getName() + ",年龄" + per.getAge());
		}
	}
}
发布了52 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43472877/article/details/104103730
今日推荐