从另一个类中设置一个Class中的ArrayList项

时间:2015-12-05 17:45:17

标签: java oop arraylist getter-setter

有一个foo类,其中一个名为double msg的ArrayList名为msgstoboo,另一个方法setMsg(int index, double input)用于更改msgstoboo中的各个邮件。

有一个networkoffoos类,其中包含名为listoffoos的foo对象的ArrayList。有updatefoomsg方法:

public void updatefoomsg (ArrayList<ArrayList<Foo>> Foonetwork)
   {
     for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
       for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
         for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
             Foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,somerandomvalue)
   }

updatefoomsg的目标是更改msgstooboo中各个消息的值。但是,foo类ArrayList`msgstoboo&#39;中没有值。被改变了。为什么这样,我该如何解决?先感谢您。

更新:以下是整个foonetworkoffoos

 public class foo
 {
  ArrayList<Double> msgstoboo = new ArrayList<Double>(Double);
  public foo(int numofmessages)
    {
     for (int i = 0; i < numofmessages; i++)
         {
         msgstoboo.add(1); 
         }
    }
  public void setMsg(int index, double input)
  {
      msgstoboo.set(index,input);
  }

&安培;&安培;

public class networkoffoos
{
    ArrayList<ArrayList<foo>> foonetwork = new ArrayList<ArrayList<foo>>();
    public void networkoffoos(int numoffoos)
    {
        for(int i = 0; i < numoffoos; i++)
        foonetwork.add(new foo(somenumberofmsgs))
    }
    //**AND THE "updatefoomsg" method included in this post**
}

1 个答案:

答案 0 :(得分:0)

以下适用于我。由于您的代码无法编译,因此进行了一些小的更改。希望它有所帮助。

import java.util.ArrayList;

public class test {
    private static ArrayList<ArrayList<Foo>> foonetwork = new ArrayList<ArrayList<Foo>>();

    public static void main(String[] args){
        networkoffoos(5);
        updatefoomsg(foonetwork);
    }

    public static void networkoffoos(int numoffoos) {
        for(int i = 0; i < numoffoos; i++) {
            ArrayList<Foo> fooArrayList = new ArrayList<Foo>();
            fooArrayList.add(new Foo(10));
            foonetwork.add(fooArrayList);
        }
    }

    public static void updatefoomsg (ArrayList<ArrayList<Foo>> foonetwork) {
        for(int foolayer = 0; foolayer< foonetwork.size(); foolayer++)
            for(int fooinlayer = 0; fooinlayer< foonetwork.get(foolayer).size(); fooinlayer++)
                for(int msginfoo = 0; msginfoo < foonetwork.get(foolayer).get(fooinlayer).msgstoboo.size(); msginfoo++)
                    foonetwork.get(foolayer).get(fooinlayer).setMsg(msginfoo,3);
    }
}

和您的Foo班级

import java.util.ArrayList;

public class Foo {
    ArrayList<Double> msgstoboo = new ArrayList<Double>();

    public Foo(int numofmessages) {
        for (int i = 0; i < numofmessages; i++) {
            msgstoboo.add(Double.valueOf(1));
        }
    }

    public void setMsg(int index, double input) {
        msgstoboo.set(index, input);
    }
}