java二维数组指定不同长度实例方法
作者:小妮浅浅 时间:2021-07-13 06:02:09
我们知道二维数组,是在一维数组的基础上进行了维度的增加。那么在实际使用的过程中,有时候我们所需要的二维数组,它们其中的维度是不同的,这就需要我们手动的进行设置。下面我们就来一起探究,二维数组在改变维度长度大小的方法,并辅以实例进行代码展示。
1、二维数组的每个元素都是一个一维数组,这些数组不一定都是等长的。声明二维数组的时候可以只指定第一维大小,空缺出第二维大小,之后再指定不同长度的数组。但是注意,第一维大小不能空缺(不能只指定列数不指定行数)。
public class ArrayTest4
{
public static void main(String[] args)
{
//二维变长数组
int[][] a = new int[3][];
a[0] = new int[2];
a[1] = new int[3];
a[2] = new int[1];
//Error: 不能空缺第一维大小
//int[][] b = new int[][3];
}
}
2、二维数组也可以在定义的时候初始化,使用花括号的嵌套完成,这时候不指定两个维数的大小,并且根据初始化值的个数不同,可以生成不同长度的数组元素。
public class ArrayTest5
{
public static void main(String[] args)
{
int[][] c = new int[][]{{1, 2, 3},{4},{5, 6, 7, 8}};
for(int i = 0; i < c.length; ++i)
{
for(int j = 0; j < c[i].length; ++j)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
实例扩展:
Java不指定长度的二维数组实例
import java.util.*;
public class Tek
{
public static void main(String[] args)
{
int[][] a=new int[3][];
a[0]=new int[3];//相当于int[] a=new int[3]
for(int i=0;i<a[0].length;i++)
a[0][i]=i+1;
a[1]=new int[4];
for(int i=0;i<a[1].length;i++)
a[1][i]=i+1;
a[2]=new int[5];
for(int i=0;i<a[2].length;i++)
a[2][i]=i+1;
for(int i=0;i<a.length;i++)
{
for(int j:a[i])
System.out.print(j+" ");
System.out.println();
}
}
}
来源:https://www.py.cn/java/shuzu/27209.html
标签:java,二维数组
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java生成指定范围随机数的多种代码
2023-04-28 07:51:15
![](https://img.aspxhome.com/file/2023/3/60383_0s.png)
springboot项目以jar包运行的操作方法
2023-11-10 07:47:43
![](https://img.aspxhome.com/file/2023/8/59328_0s.png)
logback关闭某个包的日志操作
2023-04-12 20:16:57
Java集合中的fail-fast(快速失败)机制详解
2023-05-10 16:31:33
Java中Cookie和Session详解及区别总结
2022-08-24 21:55:10
java代码执行字符串中的逻辑运算方法
2023-11-29 12:13:06
Java类的初始化顺序知识点总结
2021-09-23 23:19:26
![](https://img.aspxhome.com/file/2023/8/63748_0s.png)
java+jsp+struts2实现发送邮件功能
2023-08-28 18:25:27
![](https://img.aspxhome.com/file/2023/7/61287_0s.jpg)
Java拦截器Interceptor实现原理及代码示例
2023-11-04 03:49:32
![](https://img.aspxhome.com/file/2023/8/61528_0s.jpg)
Android解决所有双击优化的问题
2023-07-27 09:07:03
![](https://img.aspxhome.com/file/2023/0/86010_0s.png)
springboot中使用redis并且执行调试lua脚本
2022-02-15 08:49:52
![](https://img.aspxhome.com/file/2023/1/61031_0s.png)
java获取json中的全部键值对实例
2023-08-23 19:53:03
Android WindowManger实现桌面悬浮窗功能
2023-08-01 02:16:10
![](https://img.aspxhome.com/file/2023/6/84706_0s.webp)
Java Idea高效率配置技巧实例解析
2023-06-05 13:24:42
![](https://img.aspxhome.com/file/2023/7/61407_0s.jpg)
Eureka源码阅读之环境搭建及工程结构
2023-07-26 01:02:36
![](https://img.aspxhome.com/file/2023/6/57946_0s.png)
详解SpringMVC如何进行数据回显
2023-09-12 08:48:15
谈谈Java中自定义注解及使用场景
2022-08-28 04:45:39
![](https://img.aspxhome.com/file/2023/7/62717_0s.jpg)
java页面中文乱码的解决办法
2022-09-01 22:59:20
详解Spring中的Environment外部化配置管理
2023-11-23 05:24:24
![](https://img.aspxhome.com/file/2023/9/59859_0s.png)
java web中图片验证码功能的简单实现方法
2023-06-07 13:30:53