简体   繁体   English

如何在arraylist上使用自己的方法?

[英]How to use your own methods on arraylist?

public static void arrayReader(Fractions[] array)
    {
        System.out.println("This array has " + array.length + " elements");
        for(int count = 0; count < array.length; count++)
        {
            System.out.println("For cell number " + (count+1));
            array[count] = new Fractions();
            array[count].read();
        }

This is a portion of the code that I wrote. 这是我写的代码的一部分。 I was told to do the same thing except using ArrayList instead of arrays. 除了使用ArrayList而不是数组之外,我被告知要做同样的事情。 So i ran into a problem. 所以我遇到了一个问题。 how would I be able to do array[count].read(); 我怎么能做数组[count] .read();

I tried this but it wouldn't work: 我试过这个,但它不起作用:

public static void readArray(ArrayList<Fractions> array)
    {
        System.out.println("This array has " + array.size() + " elements");
        for(int count = 0; count < array.size(); count++)
        {
            Fractions fraction = new Fractions();
            fraction.read();
            array.set(count, new Fractions());
            array.add(fraction);
        }
    }

I'm not trying to have you do my homework, I'm genuinly stuck. 我不是想让你做我的作业,我被遗忘了。 So please help me understand how this could work. 所以请帮助我理解这是如何工作的。

You can use 您可以使用

array.add(count, new Fractions());

The line above is equivalent to the following line in previous code 上面的行等同于前面代码中的以下行

array[count] = new Fractions();

That is adding the new Fractions() at a specific index in the ArrayList. 那就是在ArrayList中的特定索引处添加新的Fractions()。

Similarly for the other line 对于另一条线也是如此

array[count].read();

you will have 您将拥有

(array.get(count)).read();

First of all: 首先:

 array[count] = new Fractions();

is not equivalent to: 不等于:

 array.set(count, new Fractions());
 array.add(fraction);

the arraylist.set method: arraylist.set方法:

Replaces the element at the specified position in this list
 with the specified element.

the arrayList.add method: arrayList.add方法:

Appends the specified element to the end of this list.

Use only : 仅限使用

array.add(fraction);

Then the for cycle is different 然后for循环是不同的

If your are doing: 如果你在做:

array = new ArrayList(5); //initial capacity

 for(int count = 0; count < array.size(); count++)

the size is 0. 大小为0。

If you are doing: 如果你这样做:

array = new Fractions[5]; //size

 for(int count = 0; count < array.size(); count++)

the size is 5 . 大小是5

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM