集合ArrayList中的算法,集合ArrayList算法
集合ArrayList中的算法,集合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());
相关文章
- 暂无相关文章
用户点评