集合ArrayList中的算法

//ArrayList对象比较可直接用equals比较,它会比较到每一个值


//算法代码

public class HighArray {

int[] a = new int[5];
int n = 0;


/**
* 插入元素时,如果元素的索引快到数组长度临界值,增加数组长度

* @param value
*/
public void insert(int value) {
a[n] = value;
n++;
if (n == a.length - 1) {
int[] b = new int[a.length * 2];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
// 引用
// b数组的引用,交给a,
// b数组的引用赋值给a,a指向b数组
a = b;
}
}


// 查找
public boolean find(int key) {
int i;
for (i = 0; i < n; i++) {
if (a[i] == key) {
break;
}
}
if (i <= n) {
return true;


} else {
return false;
}


}


/**
* 根据key找到其坐标
*/
public int findindex(int key) {
int i;
for (i = 0; i < n; i++) {
if (a[i] == key) {
return i;
}
}


return -1;


}


// 遍历
public void dissplay() {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
}


// 删除
public void deleteElem(int key) {
// 基本删除元素会有空间浪费
// int delindex=findindex(key);
// a[delindex]=0;
// 节省空间方式:
// 要删除的这个下标位其后的数据
// 1.找的要删除数据的下标
int delindex = findindex(key);
// 2.从这个要删除下标+1开始循环
for (int i = delindex + 1; i < n; i++) {
a[i - 1] = a[i];
a[i] = 0;
}
if (delindex > -1) {
n--;
}
// 3.遍历到每个元素,都能向前移动
}

}


//调用上述代码

HighArray arr = new HighArray();
// 添加
for (int i = 0; i < 15; i++) {
arr.insert(i);
}
arr.insert(25);
// 取得元素
arr.dissplay();


// ArrayList添加、查找
ArrayList list = new ArrayList();
for (int i = 0; i < 5; i++) {
// list.add(i, i);
list.add(i);


}
System.out.println(list.contains(4));


// 查找
boolean isfound = arr.find(15);
if (isfound) {
System.out.println("found seachkey");
} else {
System.out.println("Catn't found");
}
// 查找到key的坐标
System.out.println(arr.findindex(3));


// 删除
arr.deleteElem(2);
arr.dissplay();
}
}

//用ArraryList的方法如何实现上述的操作

//插入
ArrayList arr=new ArrayList();
arr.add(50);
for (int i = 0; i <15; i++) {
arr.add(i);
}

//遍历
System.out.println(arr.toString());


//查找
System.out.println(arr.contains(10));
//查找到其坐标
System.out.println(arr.indexOf(5));
//删除元素remove中参数是元素的位置
arr.remove(5);
//遍历
System.out.println(arr.toString());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值