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();
}
}
}
摆脱你的静态变量,因为它们不应该被用于此目的。将数组列表保存在一个类中,并调用该类的方法。 –
共享数组在这里是过度的 –