2013-05-27 42 views
2

如何在两个类之间共享阵列列表。我有一个Main类来设置应用程序的GUI,并且我试图让一个Database类执行mysql语句来存储,更新和检索数据到主类的数组列表中。类之间的共享阵列列表Java

这里就是我想要做...

主要类

public class Main 
{ 
    public static ArrayList<Animal> animal = new ArrayList<Animal>(); 
    public static ArrayList<Farm> farm = new ArrayList<Farm>(); 
    Database db; 

    public Main() { 
     db = new Database(); 
    } 

    private void addAnimal() { 
     db.animal.add(new Animal(specie, age)); 
     db.addAnimal(); 
    } 

    private void addFarm() { 
     db.farm.add(new Farm(address)); 
     db.addFarm(); 
    } 
} 

数据库类

import java.sql.*; 

public class Database 
{ 
    public static ArrayList<Animal> animal; 
    public static ArrayList<Farm> farm; 

    private Connection con = null; 
    private Statement st = null; 
    private ResultSet rs = null; 

    public Database() 
    { 
     try 
     { 
      con = DriverManager.getConnection(url, user, pw);  
      //load database entries into arraylists 
     } catch(SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public addAnimal() 
    { 
     try 
     { 
      con = DriverManager.getConnection(url, user, pw);  
      //add new animal to animal table 
     } catch(SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public addFarm() 
    { 
     try 
     { 
      con = DriverManager.getConnection(url, user, pw);  
      //add new farm to farm table 
     } catch(SQLException e){ 
      e.printStackTrace(); 
     } 
    } 
} 
+2

摆脱你的静态变量,因为它们不应该被用于此目的。将数组列表保存在一个类中,并调用该类的方法。 –

+3

共享数组在这里是过度的 –

回答

1

您需要将引用传递到您的主类的实例到您的数据库类通过它的构造函数:

所以你需要改变你的数据库控制器structor到

public Database(Main m); 

所以,当你从你的主类创建一个数据库实例,您将使用:

db = new Database(this); 

然后,您可以访问您的ArrayList,并在主任何其他实例变量类,使用:

m.animal.add()/m.animal.remove() etc. 

注 - 您还需要确保Main m是在你的数据库类的实例变量,并在它的构造函数,你需要调用

this.m = m; 

,但我想我没有必要告诉你:)