2

2 つのクラス間で配列リストを共有するにはどうすればよいですか。アプリケーションの GUI を設定するメイン クラスがあり、メイン クラスの配列リストにデータを格納、更新、取得するために mysql ステートメントを実行するデータベース クラスを作成しようとしています。

これが私がやりたいことです...

メインクラス

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

1 に答える 1