数据结构 : 顺序表
数组声明:
int[] a = new int[5];
int[] a = new int[]{2,5,3}
int[] a = {1,23,56}
数组遍历
1. for(int i=0;i<a.length;i++){//for循环
System.out.print(" %d",a[i]);
}
2. for(int item : a){//增强for循环
System.out.print(" %d",item);
}
//数据流输出:
3. Stream.of(a).forEach(System.out::print);
线性表组特点
1:快速查询
数组应用于索引有语义的情况时,但并非所有有语义情况都适合作为索引
2:增删查改
建立顺序表
package com.cxy.javaArray.myArrayList;
public class MyArrayList<T> {
T[] arr;//顺序表
int size;//顺序表的长度指针
int maxSize ; //顺序表的长度
/**
* 有参构造
* @param size 数组的长度
*/
public MyArrayList(int size){
arr = (T[]) new Object[size];
this.maxSize = size;
}
/**
* 无参构造
*/
public MyArrayList(){
arr=(T[]) new Object[0];
}
/**
* 获取顺序表的长度
*/
public int length(){
return arr.length;
}
/**
* 顺序表指定位置插入元素
* @param index 要插入的位置
* @param value 要插入的值
*/
public void insert(int index,T value) throws Exception {
if (index<0||index>this.size){
throw new Exception("ArrayListIndexOutOfLength");
}
if (index == arr.length){
throw new Exception("ArrayListIndexOutOfLength");
}
for(int i = size-1; i>index;i--) {
this.arr[i+1] = this.arr[i];
}
arr[index] = value;
size++;
}
/**
* 顺序表的追加
* @param value 要追加的元素值
*/
public void append(T value) throws Exception {
this.insert(this.size,value);
}
/**
* 顺序表的头插法
* @param value 插入的值
*/
public void addHead(T value) throws Exception {
this.insert(0,value);
}
/**
* 顺序表的指定位置删除
* @param index 下标
*/
public void remove(int index){
for(int i = index-1;i<size;i++){
arr[i] = arr[i+1];
}
arr[size]=null;
size--;
}
/**
* 对顺序表更改指定位置的值
* @param index 下标
* @param value 目标值
*/
public void alter(int index,T value) throws Exception {
if (index<0||index>size){
throw new Exception("ArrayListIndexOutOfLength");
}
arr[index] = value;
}
/**
* 顺序表是否包含目标值
* @param value 查找的目标值
* @return
*/
public int whetherIncludeIndex(T value){
boolean flag = false;
int arrIndex = -1;
for(int i = 0;i<size;i++){
if(arr[i]==value){
arrIndex = i;
}
}
return arrIndex;
}
/**
* 重写toString
* @return 0到现在位置的size处的全部数组
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
for(int i = 0;i<size;i++){
sb.append(arr[i]);
if(i==size-1)
break;
sb.append(",");
}
sb.append("]");
return sb.toString();
}
}
main函数
package com.cxy.javaArray.myArrayList;
import java.util.Arrays;
import java.util.Random;
public class Main {
public static void main(String[] args) throws Exception {
MyArrayList l1 = new MyArrayList(20);
System.out.println("增加10个数:");
for(int i = 0;i<10;i++){
l1.append(new Random().nextInt(100));
}
System.out.println(l1);;
System.out.println("更改2号位置的值为100:");
l1.alter(2,100);
System.out.println(l1);
System.out.println("删除5号位置:");
l1.remove(5);
System.out.println(l1);
}
}
>>增加10个数:
>>[32,5,96,11,89,10,42,5,60,11]
>>更改2号位置的值为100:
>>[32,5,100,11,89,10,42,5,60,11]
>>删除5号位置:
>>[32,5,100,11,10,42,5,60,11]