#001_面向对象数组

This commit is contained in:
陆小凤 2022-07-21 21:23:37 +08:00
parent fc51e1123b
commit ebe7a767c5
3 changed files with 128 additions and 0 deletions

12
data_structure/pom.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>data_structure</artifactId>
<version>1.0-SNAPSHOT</version>
</project>

View File

@ -0,0 +1,95 @@
package sort;
import java.util.Arrays;
/**
* @author Sawyer
* @date 2022/7/21
*/
public class MyArr {
private int[] elements;
public MyArr() {
elements = new int[0];
}
/**
* 获取数组长度
* @return 返回数组长度
*/
public int size(){
return elements.length;
}
/**
* 往数组末尾添加一个元素
* @param element 新元素
*/
public void add(int element){
int[] newArr = new int[elements.length+1];
System.arraycopy(elements, 0, newArr, 0, elements.length);
newArr[elements.length] = element;
elements = newArr;
}
/**
* 打印元素列表
*/
public void show(){
System.out.println(Arrays.toString(elements));
}
/**
* 通过数组下标删除元素
* @param index 数组下标
*/
public void remove(int index){
checkIndex(index);
int[] newArr = new int [elements.length-1];
for (int i = 0; i <newArr.length ; i++) {
if(i < index){
newArr[i] =elements[i];
}else {
newArr[i] = elements[i+1];
}
}
elements=newArr;
}
/**
* 通过下标获取元素
* @param index 数组下标
* @return 返回一个元素
*/
public int getElement(int index){
checkIndex(index);
return elements[index];
}
/**
* 通过指定下标添加元素
* @param index 数组下标
* @param element 元素
*/
public void insert(int index,int element){
checkIndex(index);
int[] newArr = new int[elements.length+1];
for (int i = 0; i <elements.length ; i++) {
if(i < index){
newArr[i] = elements[i];
}else {
newArr[i+1] = elements[i];
}
}
newArr[index] = element;
elements=newArr;
}
private void checkIndex(int index){
if(index <0 || index>elements.length){
throw new RuntimeException("下标越界");
}
}
}

View File

@ -0,0 +1,21 @@
package sort;
/**
* @author Sawyer
* @date 2022/7/21
*/
public class MyArrTest {
public static void main(String[] args) {
MyArr myArr = new MyArr();
myArr.add(1);
myArr.add(2);
myArr.show();
int count = myArr.getElement(0);
System.out.println(count);
myArr.size();
myArr.insert(0,22);
myArr.show();
myArr.remove(0);
myArr.show();
}
}