CoreJavaE10V1P3.10 第3章 Java的基本编程结构-3.10 数组(Arrays)
2024-10-13 02:07:57
数组是存储同一类型数据的数据结构
数组的声明与初始化
int[] a; int a[];
int[] a = new int[100];
int[] a = new int[100];
for (int i = 0; i < 100; i++)
a[i] = i; // fills the array with numbers 0 to 99
一旦创建就不可改变其大小
3.10.1 for each 循环
for each循环可以用来为数组赋值
for (variable : collection) statement
int[] a = new int[100] ;
for (int element : a)
System.out.println(element);
对数组a的每个 element 输出。
如果想直接输出数组,可以使用Arrays(java.util.Arrays )类的toString方法。
System.out.println(Arrays.toString(a));
3.10.2 数组初始化与匿名数组
int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };
匿名数组初始化:
new int[] { 17, 19, 23, 29, 31, 37 } smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };
是
int[] anonymous = { 17, 19, 23, 29, 31, 37 };
smallPrimes = anonymous;
的简写
3.10.3 复制数组
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
如果长度超出,赋值为0.
3.10.4 命令行参数
如果执行程序时使用命令 java Message -g cruel world
那么在main函数中即可接受
args[0]: "-g"
args[1]: "cruel"
args[2]: "world"
public class Message
{
public static void main(String[] args)
{
if (args.length == 0 || args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
System.out.println("!");
}
}
3.10.5 数组排序
int[] a = new int[10000];
. . .
Arrays.sort(a)
3.10.6 多维数组
double[][] balances;
int[][] magicSquare =
{
{16, 3, 2, 13},
{5, 10, 11, 8},
{9, 6, 7, 12},
{4, 15, 14, 1}
};
for (double[] row : a)
for (double value : row)
do something with value
System.out.println(Arrays.deepToString(a));快速输出2多维数组
3.10.7 不规则数组(Ragged Arrays)
Java中其实没有严格意义的多维数组,他是用数组存储的数组,每个一维数组的元素个数可以不同,类型也可不同。
最新文章
- CSS3动画制作
- Maven国内下载站点
- 文件上传时jquery.form.js中提示form.submit SCRIPT5: 拒绝访问
- ZOJ2770 Burn the Linked Camp(差分约束系统)
- ActionContext详解
- Swift闭包(Closure)
- android自动化(2)
- 【转】android开发中关于模拟器emulation的常见问题
- 正本清源区块链——Caoz
- eclipse怎么对项目重命名,eclipse怎么重命名类
- Apriori 算法python实现
- 2018.11.07 hdu1465不容易系列之一(二项式反演)
- 几个shell程序设计小知识(shell常识部分)
- 用启动器py成功解决python2和python3同时共存且同时运行的问题
- FastAdmin 线上部署流程 (2018-05-03 更新)
- Perforce查看workspace sync到的changlist
- SpringBoot - 工程搭建
- [Javascript] Conditionally spread entries to a JavaScript object
- Python使用类
- vue axios拦截器介绍