java - 将数据保存在 vector 中并在其他函数中重用

标签 java vector

我最近了解到,在编写代码时不应该使用全局变量,但在这种情况下,我需要将一些数据保存在 vector 中,以便在用户单击按钮时显示一个列表。该列表应包含 vector 中存储的信息。所以我正在考虑在点击函数中创建 vector ,但是当函数结束时, vector 将被删除。我也想过在主函数中创建 vector ,但是单击函数无法识别它。那么,是否可以将信息保存在 vector 内部,并在同一类中的其他函数中重用它,而不需要全局化该变量?

类似的东西:

private void btn_saveClientActionPerformed(java.awt.event.ActionEvent evt) {                                               
    Sale sale;
    String clientName = txtFied_Name.getText().toString();
    String product = txtField_product.getText().toString();

    sale = new Sale(clientName, product);

    vector.add(sale); // this is the variable with problems!
}                                              

private void btn_showListActionPerformed(java.awt.event.ActionEvent evt) {                                             

    List list = new List();
    list.addSales(vector);
    list.setVisible(true);
}                                            

最佳答案

I also thought about creating the vector in the main function, but the click function does not recognize it.

在应用程序中,静态 void main() 方法必须被视为一个入口点,它应该依赖类的实例来执行应用程序的逻辑和需求。因此,您应该将 vector 声明为您的类之一的实例字段(请注意,您应该更喜欢 List 而不是真正过时的 Vector)。
因此,请让我在您的示例中将 vector 替换为 list

假设您的入口点类名为 MyApp
MyApp 可以声明为:

public class MyApp{

  private List<Sale> list = new ArrayList<>();
  public static void main(String[] args){
     new MyApp();
  }


  public MyApp(){
      // init an instance of the class
  }

  // ....
  private void btn_saveClientActionPerformed(java.awt.event.ActionEvent evt) {                                               
        Sale sale;
        String clientName = txtFied_Name.getText().toString();
        String product = txtField_product.getText().toString();

        sale = new Sale(clientName, product);
        // list is now accessible as it is an instance field and a 
        //  instance method of the same class can refer to it
        list.add(sale); 
  } 

}

关于java - 将数据保存在 vector 中并在其他函数中重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51565102/

相关文章:

Javassist 和命名内部类

java - 如何在界面中声明列表(并向列表添加内容)

C++ 快速百分位数计算

c++ - 从对象 vector 中提取元素

Java - 检查文件是否在打印队列/正在使用中

java - 如何在java中将BufferedImage转换为gif

javascript - 在 Spring MVC Controller 中需要在 JS 中创建的元素的值

c++ - 一个类使用第二个类,第二个类使用第一个类中定义的结构

c++ - MTL4 将一元运算符(例如 abs())逐元素应用于 dense_vector<double>

c++ - 如何将char vector 转换为stringstream