2016-07-09 7 views
-1

Dies ist mein Code:Wie Objekt Array in der anderen Klasse hinzuzufügen, Java

public class One 
{ 
//Loots is a class 
    public static Loots[] lootsList = new Loots[] { }; 
} 

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

Bitte helfen Sie mir.
Ich möchte nicht mit List!

+1

Verwenden 'list' oder' ArrayList' statt. Viel einfacher. – SripadRaj

Antwort

0

Zugriff statische Variable und ein Verfahren einer anderen Klasse

ClassName.StaticVariable; 

OR

ClassName.StaticMethod; 

HINWEIS: - statische Variable und das Verfahren sind in aktiven gesamte Anwendung.

Verwendung dieses

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 
    } 

Codierung genießen .........

+0

Vielen Dank :) –

+0

downVote bitte kommentieren Warum tun? ...... – sushildlh

+0

Nein .. Es ist nicht ich. –

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

} 

Dies ist eine bessere Art und Weise, es zu tun, weil die Arraylist so viele Objekte wie Sie halten können brauchen, ohne dass es durch die Initialisierung der Liste definiert wird.

Wenn Sie es so definieren, wie Sie es getan haben, muss eine bestimmte Anzahl von Loots max im Array vorhanden sein.

Alternative:

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

Beispiel:

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

} 
+0

Ich möchte nicht Liste verwenden. –

+0

Wenn Sie keine Arraylist verwenden wollen, müssen Sie die Anzahl der Loots max im Array definieren – Zoe

Verwandte Themen