0

How to add object to array in an other class? This is my code:

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? 
}

I don't want to use List

1
  • 1
    Use List or ArrayList instead. Much easier. Commented Jul 9, 2016 at 9:55

2 Answers 2

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);
    }

}

This is a better way to do it because the ArrayList can hold as many objects as you need without it being defined by the initialization of the list.

BY defining it like you did, there has to be a specific amount of Loots max in the array.

Alternative:

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

Example:

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);
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to using List.
If you don't want to use arraylist you have to define the amount of Loots max in the array
0

Accessing Static variable and method of another class

ClassName.StaticVariable;

OR

ClassName.StaticMethod;

NOTE:- Static variable and Method are active in whole Application.

use this

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
    }

enjoy coding .........

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.