JAVA集合-集合的引入
发布日期:2021-09-29 01:26:58 浏览次数:8 分类:技术文章

本文共 1047 字,大约阅读时间需要 3 分钟。

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
);
    
}
}

这里我们很好的实现了用数组结构存储了三个学生,但是,

假如我们需要再存储一个学生,就懵逼了,因为长度固定了。

所以就引入了可变化长度的集合。

转载地址:https://blog.csdn.net/happydecai/article/details/80249314 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:JAVA集合-List集合
下一篇:【重要】JAVA集合类汇总

发表评论

最新留言

很好
[***.229.124.182]2024年03月26日 17时47分17秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章