我如何在两个类之间共享数组列表。我有一个设置应用程序 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();
}
}
}