数组的特点
在Java中,数组是用来存放同一种数据类型的集合,注意只能存放同一种数据类型。
//只声明了类型和长度
数据类型[] 数组名称 = new 数据类型[数组长度];//声明了类型,初始化赋值,大小由元素个数决定
数据类型[] 数组名称 = {数组元素1,数组元素2,......}
例如:整型数组
例如:对象数组
物理结构特点:
-
申请内存:一次申请一大段连续的空间,一旦申请到了,内存就固定了。
-
不能动态扩展(初始化给大了,浪费;给小了,不够用),插入快,删除和查找慢。
-
存储特点:所有数据存储在这个连续的空间中,数组中的每一个元素都是一个具体的数据(或对象),所有数据都紧密排布,不能有间隔。
具体的,如下图:
自定义数组
package com.atguigu01.overview.array;
/**
* @author 尚硅谷-宋红康
* @create 14:39
*/
class Array {
private Object[] elementData;private int size;
public Array(int capacity){
elementData = new Object[capacity];
}/**
* 添加元素
* @param value
*/
public void add(Object value){
if(size >= elementData.length){
throw new RuntimeException("数组已满,不可添加");
}
elementData[size] = value;
size++;
}/**
* 查询元素value在数组中的索引位置
* @param value
* @return
*/
public int find(Object value){
for (int i = 0; i < size; i++) {
if(elementData[i].equals(value)){
return i;
}
}
return -1;
}/**
* 从当前数组中移除首次出现的value元素
* @param value
* @return
*/
public boolean delete(Object value){
int index = find(value);
if(index == -1){
return false;
}for(int i = index;i < size - 1;i++){
elementData[i] = elementData[i + 1];
}
elementData[size - 1] = null;
size--;
return true;
}/**
* 将数组中首次出现的oldValue替换为newValue
* @param oldValue
* @param newValue
* @return
*/
public boolean update(Object oldValue,Object newValue){
int index = find(oldValue);
if(index == -1){
return false;
}
elementData[index] = newValue;
return true;}
/**
* 遍历数组中所有数据
*/
public void print(){
System.out.print("{");
for (int i = 0; i < size; i++) {
if(i == size - 1){
System.out.println(elementData[i] + "}");
break;
}
System.out.print(elementData[i] + ",");
}
}
}//测试类
public class ArrayTest {
public static void main(String[] args) {
Array arr = new Array(10);arr.add(123);
arr.add("AA");
arr.add(345);
arr.add(345);
arr.add("BB");arr.delete(345);
arr.update(345,444);
arr.print();
}
}