首页 > 编程语言 > 详细

编写一个SuperArray类,实现对数组的增删改查以及排序等方法,类似于ArrayList,可以重复的添加或者删除

时间:2021-03-06 23:41:36      阅读:44      评论:0      收藏:0      [点我收藏+]
package study04;

public class SuperArray {

private int[] array;
private int currentIndex = -1;

public SuperArray(){
array = new int[5];
}

public SuperArray(int size){
array = new int[size];
}
// public void add(int number){
// currentIndex++;
// if (currentIndex>=array.length){
// int[] temp = new int[array.length*2];
// for (int i = 0; i < array.length; i++) {
// temp[i]=array[i];
// }
// array = temp;
// }
// array[currentIndex] = number;
// }
public SuperArray add(int number){
currentIndex++;
if (currentIndex>=array.length){
int[] temp = new int[array.length*2];
for (int i = 0; i < array.length; i++) {
temp[i]=array[i];
}
array = temp;
}
array[currentIndex] = number;
return this;
}

public SuperArray remove(int index){
if (index>currentIndex){
System.out.println("输入非法");
}else {
for (int i = index; i < currentIndex; i++) {
array[i] = array[i + 1];
}
currentIndex--;
}
return this;
}

public void set(int index,int number){
if (index>currentIndex){
System.out.println("输入非法");
}else {
array[index] = number;
}
}

public int get(int index){
if (index>currentIndex){
System.out.println("输入非法");
}else {
return array[index];
}
return 0;
}

public void sort(){
int temp;
for (int i = 0; i < currentIndex; i++) {
for (int j = 0; j < currentIndex - i; j++) {
if (array[j]>array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
}

public void print(){
String s = "[";
for (int i = 0; i <= currentIndex; i++) {
if (i==currentIndex){
s+=array[i];
} else {
s+=array[i]+",";
}
}
s+="]";
System.out.println(s);
}
}

技术分享图片

编写一个SuperArray类,实现对数组的增删改查以及排序等方法,类似于ArrayList,可以重复的添加或者删除

原文:https://www.cnblogs.com/wenrou-pan/p/14491963.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!