文章目录
java数据结构:数组
int[] Test_list= new int[] {1,7,9,-1,5,11};
刚学java,发现上面这种代码在很多文章中都被称为数组,但是这种数据结构似乎更像是一个存储结构,作为数据结构来说其增删改查操作以及遍历操作都需要单独写函数实现。
而数据结构一书当中的数组概念其实对应ArrayList. 通过简单的代码了解一下这种数据结构。
首先是增加:
Test_array.add(100);
删除:
Test_array.remove(2); // 参数是index
修改:
Test_array.set(0,1000);
查找:
Test_array.indexOf(7)
排序:
Collections.sort(Test_array);
以及java和c++类似,都运用了迭代器这个概念来遍历数据结构。(因为python都是用for循环),对我来说是件新鲜事。
//迭代器遍历.
Iterator<Integer> it = Test_array.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
完整代码如下,eclipse版本-Release 4.26,java版本- 1.0.7_45 :
package TestOperation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Collections;
public class List {
public static void main(String[] args){
int[] Test_list= new int[] {1,7,9,-1,5,11};
print_list(Test_list);
Arrays.sort(Test_list);
print_list(Test_list);
// 上述定义的数组只能进行初始化,增删改查算法都要重新写。
//
ArrayList<Integer> Test_array =new ArrayList<Integer>(Arrays.asList(1,7,9,-1,5,11));
System.out.println(Test_array);
//迭代器遍历.
Iterator<Integer> it = Test_array.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println();
// 添加元素.
Test_array.add(100);
System.out.println(Test_array);
//删除元素.
Test_array.remove(2); // 参数是index
System.out.println(Test_array);
// 修改元素.
Test_array.set(0,1000);
System.out.println(Test_array);
// 查找元素.
System.out.println(Test_array.indexOf(7));
//数组排序.
Collections.sort(Test_array);
System.out.println(Test_array);
//数组大小. // Test_array.size()
}
public static void print_list(int[] array) {
for(int i=0;i<array.length;i++) {
if(i!=0) {System.out.print(',');}
System.out.print(array[i]);
}
System.out.println();
}
}