简体   繁体   中英

Shared arraylists between classes Java

How do i share arraylists between two classes. I have a Main class that sets the GUI of the application, and i'm trying to make a Database class that executes mysql statements to store, update and retrieve the data into the arraylists of the Main Class.

Here is what i am wanting to do...

Main class

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

Database class

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

You need to pass a reference to an instance of your Main class into your Database class via its constructor:

So you need to change your Database constructor to

public Database(Main m);

So, when you create a Database instance from your Main class, you'll use:

db = new Database(this);

Then, you can access your ArrayLists, and any other instance variables in your Main class, using:

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

NOTE - you'll also need to make sure Main m is an instance variable in your Database class, and in its constructor you'll need to call

 this.m = m;

But I'm guessing I don't need to tell you that :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM