简体   繁体   English

为什么不能将list.size设置为整数数组的长度?

[英]Why can't I set list.size as the length of my integer array?

I've been struggling for hours to eliminate a bug that I don't understand. 我一直在努力消除我不了解的错误。 In line 190 of the code below (int s = n[0]) I get an array out of bounds exception which as I've narrowed down has to do with array e. 在下面的代码的第190行(int s = n [0])中,我得到了数组超出范围的异常,这与我缩小范围与数组e有关。 Array e is declared at the top of the code given below with the length/size of an object list a (a.size()) and if I replace size with an arbitrary integer (for example 10) the error disappears. 数组e在下面给出的代码的顶部声明,带有对象列表a的长度/大小(a.size()),如果我用任意整数(例如10)替换size,错误消失。

Why can't I set a.size as the length of my array? 为什么不能将a.size设置为数组的长度? Is there a way to go around this? 有办法解决这个问题吗?

Summary of the code: powerize(int n) is supposed to Write a number n as a power with maximal exponent. 代码摘要:powerize(int n)应该写一个数字n作为具有最大指数的幂。 factorize decomposes a number into the product of primes and gcd returns the greatest common divisor of an array of integers. factorize将数字分解为素数的乘积,而gcd返回整数数组的最大公约数。

public static Power powerize(int n) throws IllegalArgumentException {

    List<Power> a = MathStuff.factorize(n); //make a list of Power objects from factorize n
    int size = a.size();
    int[] e = new int[size];
    int[] b = new int[size];

    for (int i = 0; i < size; i++) { //collect all the base and exponent of each object in a. This LOOP 1
        if(i >= a.size() || i >= e.length || i > b.length){System.out.print("Out of bounds in LOOP 1");} //test for out of bounds
        e[i] = a.get(i).exponent;
        b[i] = a.get(i).base;
    }

    int g = gcd(e);


    int h = 1; //endproduct base
    for (int i = 1; i < b.length; i++) { //Construct the base by taking the product of each base with its exponent divided by g.
        if(i >= e.length || i >= b.length){System.out.print("Out of bounds in LOOP 3");} //test for out of bounds
        h *= MathStuff.power(b[i], e[i] / g);
    }

    return new Power(h, g); //replace 2

}


/**
 * factorize n
 *
 * @param n the number to 'powerize'
 * @modifies none
 * @pre {@code 2 <= n}
 * @return factorization of n
 */
public static List<Power> factorize(int n) {
    List<Integer> f = new ArrayList<Integer>(); // f are factors
    for (int i = 2; i <= n; i++) {
        while (n % i == 0) {
            f.add(i);
            n /= i;
        }
    }
    //return f; //returns factors

    List<Power> p = new ArrayList<Power>(); // p are the factors with powers
    for (int j = 2; j <= n; j++) { //j will be the base
        int e = 0; //exponent
        for (int k = 0; k <= f.size(); k++) {
            if (f.get(k) == j) {
                e++;
            }
        }
        p.add(new Power(j, e));
    }

    return p; //returns factors in powered form
}

/**
 * gcd returns the greatest common divisor of an integer array
 * @param n
 * @return greatest common divisor
 */
public static int gcd(int... n) {

    //------------------------------------------------THE ERROR OCCURS HERE
    int s = n[0];

    for (int i = 1; i < n.length; i++) {
        if (n[i] < s) {
            s = n[i];
        }
    }

    while (s > 1) {

        int counter = 0;
        int modTot = 0;

        while (counter < n.length) {

            modTot += n[counter] % s;
            counter++;

        }

        if (modTot == 0) {
            return s;
        }

        s--;

    }
    //return 0 if there is no gcd
    return 0;
}   

Here: 这里:

public static int gcd(int... n) {
 int s = n[0];

This code assumes (without any further checking) that gcd() was invoked with at least one array element. 该代码假定 (无需进一步检查gcd()已使用至少一个数组元素调用了gcd() But obviously that is not true. 但是显然那是不正确的。

Keep in mind that you can invoke that method like: 请记住,您可以像以下那样调用该方法:

gcd(); // NO array at all or
gcd(someArray); // but someArray happens to be null !

So you have to step back and check your source code for all situations where gcd() is called. 因此,对于所有调用gcd()情况,您都必须退后一步并检查源代码。 There must be one where you pass 0 parameters; 您必须在其中传递0个参数的地方; or you pass an array of int that is actually null. 或者您传递实际上为null 的int数组

I'll assume that your question is why you can't set the size of an array using the size property. 我假设您的问题是为什么您不能使用size属性设置数组的size

When an array is initialized (via new int[x] ), the OS will look for a continuous block of memory that will be big enough to hold x int s. 初始化数组(通过new int[x] )时,操作系统将寻找连续的内存块,该内存块应足以容纳x int Once that memory is found, the size of the array will be fixed as x . 找到该内存后,数组的大小将固定为x

Think of what would happen if you could change the array size using size . 想想如果您可以使用size更改数组大小会发生什么。 This would mean that, if you wanted to expand this array, you would have to take over the memory that comes immediately after it. 这意味着,如果要扩展此数组,则必须接管紧随其后的内存。 What if that memory is being used by something else? 如果该内存被其他人使用怎么办? That would present a problem. 那会带来问题。

However, java.util.ArrayList solves this problem for you as and when necessary. 但是, java.util.ArrayList在必要时为您解决此问题。 So that's the work-around if you need it. 因此,这是您需要的解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 继续调用 array.length 或 list.size() 的性能损失 - Performance loss of continued call to array.length or list.size() 为什么recyclerview不添加所有list.size? - Why the recyclerview don't add all list.size? for(int i = 0,length = list.size; i有什么区别 - What is the difference between “for(int i=0,length=list.size;i<length;i++) ” and “for(int i=0;i<list.size;i++) ”? 为什么 list.size()&gt;0 在 Java 中比 list.isEmpty() 慢? - Why is list.size()>0 slower than list.isEmpty() in Java? 为什么运行时间复杂(清单 <Object> )list.size()是O(1)吗? - Why the running time complexity of (List<Object>) list.size() is O(1)? 在Java中列出类的toArray-为什么我不能将“Integer”列表转换为“Integer”数组? - List class's toArray in Java- Why can't I convert a list of “Integer” to an “Integer” array? 为什么我不能复制/转换列表 <Set<String> &gt;进入SortedMap <Set<String> ,整数&gt;? - Why can't I copy/convert a List<Set<String>> into a SortedMap<Set<String>,Integer>? !list.isEmpty() 和 list.size()&gt;0 是否相等? - Is !list.isEmpty() and list.size()>0 equal? 相当于BitSet的list.size()是什么? - Whats the list.size() equivalent of the BitSet? 想知道这条线是如何工作的。 int j = list.size() - i - 1; - Want to know how does this line work. int j = list.size() - i - 1;
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM