创建数字数组不循环? [英] Creating an array of numbers without looping?

查看:96
本文介绍了创建数字数组不循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我使用JavaMail库,我试图获取某些消息编号。我想这样做有效,不必过度东西两次循环...反正我对你的问题是:如何创建开始于指数 X ,并在指数结束数组 X - 11 不用循环


解决方案

如果你想创建和填充一个数组,你基本上有三种选择:


  1. 明确写值: INT [] = NUM​​S新INT [] {0,1,2,3,4,...}


  2. 使用某种形式的for循环:的for(int i = 0;我小于10;我++){NUMS [我] =我; }


  3. 递归创建它:



INT [] = NUM​​S新INT [12];
NUMS =填充(0,X,NUMS);私人诠释[]填充(INT指数,诠释的x,INT [] NUMS){
    如果(nums.length> =指数){
        返回NUMS;
    }其他{
        NUMS [指数] = X - 指数; //的x 0到x-11
        返回填充(指数+1,X,NUMS);
    }
}

香草的Java,没有额外的库和诸如此类的东西,不支持地图功能将允许你指定一个函数,会以某种方式自动生成你的价值观。

不过,我真的不明白,为什么你不希望使用一个循环,尤其是对于像这样的一些小事。

Okay so I am using the JavaMail library and I am trying to fetch certain message numbers. I want to do it efficiently and not have to loop twice over something… Anyways my question to you is: How can I create an array that starts at index x and ends at index x - 11 without looping?

解决方案

If you want to create and populate an array, you have basically three options:

  1. Write the values explicitly: int[] nums = new int[] { 0, 1, 2, 3, 4, ... }

  2. Use some form of for-loop: for (int i = 0; i < 10; i++) { nums[i] = i; }

  3. Create it recursively:

int[] nums = new int[12];
nums = populate(0, x, nums);

private int[] populate(int index, int x, int[] nums) {
    if (nums.length >= index) {
        return nums;
    } else {
        nums[index] = x - index; // x-0 through x-11
        return populate(index+1, x, nums);
    }
}

Vanilla Java, without extra libraries and whatnot, doesn't support a map function which would allow you to specify a function that would somehow auto-generate your values.

Though, I really don't understand why you don't want to use a loop, especially for something trivial like this.

这篇关于创建数字数组不循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆