如何在Java中声明和初始化数组?
当前回答
有两种类型的阵列。
一维阵列
默认值的语法:
int[] num = new int[5];
或(不太优选)
int num[] = new int[5];
给定值的语法(变量/字段初始化):
int[] num = {1,2,3,4,5};
或(不太优选)
int num[] = {1, 2, 3, 4, 5};
注意:为了方便起见,最好使用int[]num,因为它清楚地告诉您在这里讨论的是数组。否则没有区别。一点也不。
多维数组
公告
int[][] num = new int[5][2];
Or
int num[][] = new int[5][2];
Or
int[] num[] = new int[5][2];
初始化
num[0][0]=1;
num[0][1]=2;
num[1][0]=1;
num[1][1]=2;
num[2][0]=1;
num[2][1]=2;
num[3][0]=1;
num[3][1]=2;
num[4][0]=1;
num[4][1]=2;
Or
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
杂乱阵列(或非矩形阵列)
int[][] num = new int[5][];
num[0] = new int[1];
num[1] = new int[5];
num[2] = new int[2];
num[3] = new int[3];
所以这里我们是显式定义列。另一种方式:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
用于访问:
for (int i=0; i<(num.length); i++ ) {
for (int j=0;j<num[i].length;j++)
System.out.println(num[i][j]);
}
或者:
for (int[] a : num) {
for (int i : a) {
System.out.println(i);
}
}
杂乱数组是多维数组。有关说明,请参阅官方java教程中的多维数组详细信息
其他回答
公告
一维阵列
int[] nums1; // best practice
int []nums2;
int nums3[];
多维数组
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
声明和初始化
一维阵列
使用默认值
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
带数组文字
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
带有循环
int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
nums[i] = i; // can contain any YOUR filling strategy
}
Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
objects[i] = new Object(); // can contain any YOUR filling strategy
}
带循环for和Random
int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
nums[i] = random.nextInt(10); // random int from 0 to 9
}
使用流(从Java 8开始)
int[] nums1 = IntStream.range(0, 3)
.toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
.toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
.toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
.sorted()
.toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
.toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
.takeWhile(x -> x < 3)
.toArray(); // [0, 1, 2]
int size = 3;
Object[] objects1 = IntStream.range(0, size)
.mapToObj(i -> new Object()) // can contain any YOUR filling strategy
.toArray(Object[]::new);
Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
.limit(size)
.toArray(Object[]::new);
使用Random和Stream(从Java 8开始)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
多维数组
使用默认值
int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]
带数组文字
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
带有循环
int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; i++) {
nums[i][j] = i + j; // can contain any YOUR filling strategy
}
}
Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < nums[i].length; i++) {
objects[i][j] = new Object(); // can contain any YOUR filling strategy
}
}
为Java 8和更高版本声明和初始化。创建一个简单的整数数组:
int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
为[-50,50]之间的整数和双[0,1E17]创建随机数组:
int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
两个序列的功率:
double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]
对于String[],必须指定构造函数:
String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));
多维数组:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
另一种声明和初始化ArrayList的方法:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
电影类的另一个完整示例:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
制作阵列有两种主要方法:
对于空数组:
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
对于一个初始化的数组:
int[] array = {1,2,3,4 ...};
您还可以创建多维数组,如下所示:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何读一个文本文件到一个列表或数组与Python
- 如何找到Java堆大小和内存使用(Linux)?
- 如何在Python中将十六进制字符串转换为字节?
- 使用Enum实现单例(Java)
- 与push()相反;
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 用“+”(数组联合运算符)合并两个数组如何工作?