JAVA集合-集合的引入
当我们有种需求,需要存储多个元素的结构时,我们前面讲过数组,数组可以存储。但是数组也有它的弊端,使用的时候,
必须先定义好长度,也就是数组的长度是固定,不能根据我们的需求自动变长或者变短。
我们看一个实例:
先定义一个Student类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.java1234.chap08.sec01; public class Student { private String name; private Integer age; public Student() { super (); // TODO Auto-generated constructor stub } public Student(String name, Integer age) { super (); this .name = name; this .age = age; } public String getName() { return name; } public void setName(String name) { this .name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this .age = age; } } |
然后我们需要存储三个学生信息:
我们给下测试类:
1 2 3 4 5 6 7 8 9 10 11 | package com.java1234.chap08.sec01; public class Test { public static void main(String[] args) { Student students[]= new Student[ 3 ]; students[ 0 ]= new Student( "张三" , 1 ); students[ 1 ]= new Student( "李四" , 2 ); students[ 2 ]= new Student( "王五" , 3 ); } } |
这里我们很好的实现了用数组结构存储了三个学生,但是,
假如我们需要再存储一个学生,就懵逼了,因为长度固定了。
所以就引入了可变化长度的集合。