【问题标题】:How to add object to array in the other class, Java如何将对象添加到另一个类中的数组,Java
【发布时间】:2016-07-09 09:50:18
【问题描述】:

如何将对象添加到其他类的数组中? 这是我的代码:

public class One
{
   //Loots is a class  
   public static Loots[] lootsList = new Loots[] { };
}   
 
public class Two
{ 
   Loots MyLoots = new Loots();         
   // How to add MyLoots to lootsList in THIS class? 
}

我不想使用列表

【问题讨论】:

  • 请改用ListArrayList。容易得多。

标签: java android arrays android-studio


【解决方案1】:
public class One{
   public List<Loots> lootsList = new ArrayList<Loots>();

   public void someVoid(){
       new Two(this);
   }
}   

public class Two
{ 
    One one;
    public Two(One one){
        this.one = one:
    }

   Loots MyLoots = new Loots();         
   // How to add in THIS class, MyLoots to lootsList? 

    public void someVoid(){
        one.lootsList.add(MyLoots);
    }

}

这是一种更好的方法,因为 ArrayList 可以根据需要保存任意数量的对象,而无需通过列表的初始化来定义它。

通过像您一样定义它,数组中必须有特定数量的 Loots max。

替代方案:

public static Loots[] lootsList = new Loots[20];

例子:

public class One{

    public static Loots[] lootsList = new Loots[20];
    public void someVoid(){
       new Two(this);
    }
}   

public class Two
{ 
    One one;
    public Two(One one){
        this.one = one:
    }

   Loots MyLoots = new Loots();         
   // How to add in THIS class, MyLoots to lootsList? 

    public void someVoid(){
        one.lootsList[0].add(MyLoots);
    }

}

【讨论】:

  • 我不想使用 List。
  • 如果你不想使用arraylist,你必须在数组中定义Loots max的数量
【解决方案2】:

访问另一个类的静态变量和方法

ClassName.StaticVariable;

ClassName.StaticMethod;

注意:- 静态变量和方法在整个应用程序中都处于活动状态。

使用这个

public class One
    {
       public static Loots[] lootsList = new Loots[1];
    }   

    public class Two
    { 
       Loots MyLoots = new Loots();         
       // How to add in THIS class, MyLoots to lootsList? 
       One.Loots[0]=MyLoots; //use this to access array of objects
    }

享受编码............

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2022-08-13
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多