4.1.1一维数组
1.数组:
在java中,数组是用来存储一组相同类型数据的数据结构;当数组初始化完毕后,java为数组在内存中分配一段连续的空间,其在内存中开辟的空间也随之固定,此时数组的长度就不能发生改变;即使数组中没有保存任何数据,数组占据的空间依然存在;
2.定义数组
数据类型 [ ] 数组名 = new 数据类型[数组长度];
数据类型 数组名 [ ] = new 数据类型[数组长度];
----数组长度决定连续分配的空间的个数,通过数组的length属性获取长度;
----数据类型 用于确定分配的每个空间的大小;
例子:
int [ ] scores = new int[5];----为数组scores分配了5个连续空间,每个空间存储整型的数据, 占用4个字节,每个空间值是0;
String cities [ ] = new String[6];----为数组scores分配了6个连续空间 , 用来存储字符串类型的数据,每个空间的值是null;
数组分配初始值:
byte / short / int / long 0
float / double 0.0
char '\u0000'
boolean false
引用数据类型 null
3.数组元素的表示与赋值
例子: scores[0] = 65 ;//表示为scores数组中的 第一个元素赋值65;
4.数组的初始化
(1)数据类型[ ] 数组名 = {值1 , 值2 , 值3 , 值4 , ...... , 值n};
(2)数据类型[ ] 数组名 = new 数据类型[ ] {值1 , 值2 , 值3 , 值4 , ...... , 值n};
5.遍历数组
编写程序时,数组和循环往往结合在一起使用,可以大大简化代码,提高程序编写程序,通常使用for循环遍历数组;
例子:
public static void main(String[] args){
int scores[] = new int[5]; //创建长度为5的整型数组;
Scanner input = new Scanner(System.in);
for(int i = 0; i< scores.length ; i++){ //scores.length等于数组的长度5
score[i] = input.nextInt(); //从控制台接收键盘输入,进行循环赋值;
}
}
增强for循环的语法:
for(元素类型 变量名 : 要循环的数组或集合名){......}
例子:
public static void main(String[] args) {
int scores[] = {75,67,90,100,0};
for(int i : scores){
System.out.println("数组元素值依次为:"+i);
}
}
数组添加:
例子
public static void main(String[] args) {
int index = -1;
String[] phones = {"iphone4", "iphone4s" , "iphone5",null};
for(int i = 0; i<phones.length ; i++){
if(phones[i] == null){
index = i;
break;
}
}
if(index != -1){
phones[index] = "iphone5S";
for(int i = 0; i<phones.length ; i++){
System.out.println(phones[i]);
}
}else{
System.out.println("数组已满");
}
}
以上代码解析:
index变量相当于一个监视器,赋值初始值-1 为了和数组下标的0 、1 、2 等区分开来。遍历数组的元素,如果发现了null就会把i赋值给index, 相当于找到null的下标,此时使用break跳出循环;
下一个if语句, 首先判断index的值是否变化,若变化(-1) , 说明发现null的元素 ,此时找到空的位置赋值“iphone5s”
数组修改:
与数组添加类似,但在第二个if语句中,找到需要修改的位置, 对该位置重新赋值;
数组删除:
思路:找到需要删除的位置,删除后把后面的数据依次前移,将最后一位设置为null;
public static void main(String[] args) {
String[] phones = {"iPhone3GS经典" ,"iPhone革新","iPhone4S变化不大","iPhone5掉漆"};
int index = -1;
for(int i =0; i< phones.length ; i++){
if(phones[i].equals("iPhone3GS经典")){
index = i;
break;
}
}
if(index != -1){
for(int i = index ; i < phones.length-1 ;i++ ){
phones[i] = phones[i+1];
}
phones[phones.length-1] = null;
}else{
System.out.println("没有您要删除的内容!");
}
for(int k = 0 ; k<phones.length ; k++){
System.out.println(phones[k]);
}
}