数组
来源:互联网 发布:阳春巿网络问政 编辑:程序博客网 时间:2024/05/16 19:24
数组与容器比较
- 数组作为一个简单的线性序列,访问效率要优于容器,但是缺点是对象的大小不能改变。
- 数组可以持有基本数据类型,但是容器只能持有包装类(但是由于自动拆箱和装箱,使得差别不大)。
- 应该优先选择容器而不是数组,因为容器的灵活性要远远大于数组。除非性能已经成为瓶颈。
数组创建的过程
数组创建其实是分两步进行的:
1. 开辟一段空间,对于对象类型来说这段空间保存的是引用,而基本数据类型直接保存基本类型的值。数组空间创建好之后会自动赋初始值。引用为 null,而数值型为 0 ,char 型为 (char)0,布尔型为 false。
2. 对数组进行赋值。
数组初始化的两种方式
//非聚合方式,在参数传递等任何地方都可以使用Integer[] array = new Integer[]{1,2,3};//聚合方式(隐式使用 new 在堆中创建),只能在定义数组时使用Integer[] array = {1,2,3};
多维数组
多维数组其实就是保存数组引用的数组,数组中构成矩阵的每个向量都可以具有任意的长度(称为粗糙数组)。
Integer[][] array = new Integer[2][];array[1] = new Integer[]{1,2,3};array[2] = new Integer[]{8,9,4,3,1};
数组操作
public class ArrayTest { public static void main(String[] args){ MyElement obj1 = new MyElement(3,2); MyElement[] array = new MyElement[3]; //填充,对象是填充引用 Arrays.fill(array,0,3,obj1); System.out.println(Arrays.toString(array)); array[1].setX(2).setY(1); System.out.println(Arrays.toString(array)); //浅复制 MyElement[] copeArray = Arrays.copyOf(array,5); System.out.println(Arrays.toString(copeArray)); copeArray[1].setX(3).setY(2); System.out.println(Arrays.toString(copeArray)); //排序 copeArray[1] = new MyElement(4,1); copeArray[2] = new MyElement(6,5); copeArray[3] = new MyElement(2,2); copeArray[4] = new MyElement(5,4); Arrays.sort(copeArray); System.out.println(Arrays.toString(copeArray)); Arrays.sort(copeArray, new Comparator<MyElement>() { public int compare(MyElement o1, MyElement o2) { if(o1.getY() == o2.getY()) return 0; return o1.getY() > o2.getY() ? 1 : -1; } }); System.out.println(Arrays.toString(copeArray)); //通过comperable 查找 System.out.println(Arrays.binarySearch(copeArray,new MyElement(3,1))); System.out.println(Arrays.binarySearch(copeArray, new MyElement(3, 1), new Comparator<MyElement>() { public int compare(MyElement o1, MyElement o2) { if(o1.getX() == o2.getX()){ if(o1.getY() == o2.getY()) return 0; return o1.getY() > o2.getY() ? 1 : -1; } return o1.getX() > o2.getX() ? 1 : -1; } })); }}class MyElement implements Comparable<MyElement>{ private int x; private int y; public MyElement(int x, int y){ this.x = x; this.y = y; } public MyElement setX(int x){ this.x = x; return this; } public MyElement setY(int y){ this.y = y; return this; } public int getX(){ return x; } public int getY(){ return y; } @Override public String toString(){ return "[" + x + "," + y + "]"; } public int compareTo(MyElement o) { if(this.x == o.x) return 0; return this.x > o.x ? 1 : -1; }}
0 0
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- NEOS Server: State-of-the-Art Solvers for Numerical Optimization
- java中正则表达式的详解
- python学习笔记(一)
- .htaccess文件说明大全
- 165. Compare Version Numbers
- 数组
- C++:对象数组、对象动态申请和释放、类的定义和实现分开、this指针、常成员函数、时钟
- C(1)——常量与变量
- Matlab编程与数据类型 -- 数据类型概述
- Ionic Grid栅格布局居中实例
- C10-1 单词计数
- CCF201312-3 最大的矩形(解法二)(100分)
- LEAPMotion猎户座(VR)开发~003~UI
- HDU 1075 What Are You Talking About (字典树)