您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
三六零分类信息网 > 南平分类信息网,免费分类信息发布

如何在Java中将二维数组转换为一维数组

2025/11/20 20:57:00发布43次查看
将二维数组转化为一维数组1. 为了偷懒所以我写了一个随机生成二维数组的函数
/* * 自动创建随机为100以内的二维数组: int nums[x][y] * */ public static int[][] createddemarray(int x,int y){ int nums[][]=new int[x][y]; for(int i=0;i<nums.length;i++){ for(int j=0;j<nums[i].length;j++){ nums[i][j]=(int)(math.random()*100); } } return nums; }
2. 定义一个5x8的二维函数
public static void main(string[] args) { createdarray ca=new createdarray(); int nums[][]=createddemarray(5,8); }
3. 定义一个长度为40 的int 数组,并使用system.arraycopy的方式将二维数组填充到一维数组temp中
public static void main(string[] args) { createdarray ca=new createdarray(); int nums[][]=createddemarray(5,8); //定义整数数组 int[] temp=new int[40]; //通过 arraycopy方法来将二维数组填充到一维数组temp中 for(int i=0;i<nums.length;i++){ system.arraycopy(nums[i],0,temp,i*8,8); } }
4. 如果填充到一维数组之后我想搞点事,把一维数组进行排序后,回填到二维数组中
public static void main(string[] args) { createdarray ca=new createdarray(); int nums[][]=createddemarray(5,8); int[] temp=new int[40]; for(int i=0;i<nums.length;i++){ system.arraycopy(nums[i],0,temp,i*8,8); } // 对一维数组进行排序 arrays.sort(temp); // 将排序后的数组进行回填 int index=0; while (index<temp.length){ for(int i=0;i<nums.length;i++){ for(int j=0;j<nums[i].length;j++){ nums[i][j]=temp[index++]; } } } system.out.println("排序后的数组如下"); // 这里因为懒所以我自定义了一个函数 打印二维数组 showdemarray(nums); }
5. 补充一下上面用到的打印二维数组
/* * 输出二维数组 * 这里我不知道怎么写我还去问了我前任:) 因为我实在不知怎么传这个参 * 如果要做成通用的比如说既能打印整数类型又能打印字符串类型的二维数组需要用的泛型... * 毕业2年我已经忘了泛型怎么用,下次再补补 */public static void showdemarray(int[][] nums){ for (int i=0;i<nums.length;i++){ for (int j=0;j<nums[i].length;j++){ system.out.print(nums[i][j]+"\t"); if((j+1)%nums[i].length==0){ system.out.println(); } } } }
今天也是想当测开的一天
一维数组转化为二维数组由于经常在使用矩阵进行计算时,会首先将一维数组转为二维数组。因此,在这里记录一下,也希望对他人有帮助。
package deal;/* * author:合肥工业大学 管院学院 钱洋 *1563178220@qq.com*/public class arrytest { public static void main(string[] args) { //创建一个一维数组 0,1,2,3...,10 double [] c= new double[10]; for (int i = 0; i < c.length; i++) { c[i]=i; } double[][] testarr=twoarry(c); for (int i = 0; i < testarr.length; i++) { for (int j = 0; j < testarr[i].length; j++) { system.out.println(testarr[i][j]); } } } //一维数组转化为二维数组 public static double[][] twoarry(double[] onedouble){ double[][] arr=new double[1][onedouble.length]; for (int i = 0; i < onedouble.length; i++) { arr[0][i]=onedouble[i]; } return arr; }}
程序运行结果。
以上就是如何在java中将二维数组转换为一维数组的详细内容。
南平分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product