【问题标题】:Acces an array list from another class to use in method从另一个类访问数组列表以在方法中使用
【发布时间】:2016-09-28 16:43:14
【问题描述】:

我正在尝试从另一个类中获取对象的数组列表以显示它并对其进行修改(删除 ArrayList 中的对象),因此也必须修改原始 ArrayList...我尝试了以下方法,但未成功。

类属性

private int number; //user imput

方法

public String DisplayObj() {
    String result;
    FormularioPedido form = new FormularioPedido(); //instance of the other class so I can access the arrayList
    ArrayList<Pedido> lista = form.getListaPedido();

    number -= 1;
    Pedido pedido = lista.get(number);
    result = pedido.getTamanio() + pedido.getIngredientesToString()
            + pedido.getBebida() + pedido.getExtra() + pedido.getCelular();
    return result;
}

public void deleteObj() {

    FormularioPedido form = new FormularioPedido();
    List<Pedido> lista = form.getListaPedido();

    number -= 1;
    lista.remove(number);

}

【问题讨论】:

  • 您每次都在重新创建new FormularioPedido();。尝试将其设为全局(类)变量?

标签: java object arraylist methods


【解决方案1】:

每次您写new FormularioPedido() 时,都会创建一个新列表(当您调用form.getListaPedido() 时返回)。你应该多考虑一下你的类设计。例如,列表可以是类属性,您可以对同一个列表实例进行操作。

【讨论】:

    【解决方案2】:

    您需要将列表存储为 Class 属性。 这样,您显示的列表将与您要删除的列表相同。

    目前它是 2 个单独的列表,每次调用显示方法时都会重新创建一个。

    private int number; //user imput
    private FormularioPedido form  = new FormularioPedido();
    
    public String DisplayObj() {
        String result;
        ArrayList<Pedido> lista = form.getListaPedido();
    
        number -= 1;
        Pedido pedido = lista.get(number);
        result = pedido.getTamanio() + pedido.getIngredientesToString()
                + pedido.getBebida() + pedido.getExtra() + pedido.getCelular();
        return result;
    }
    
    public void deleteObj() {
    
        List<Pedido> lista = form.getListaPedido();
    
        number -= 1;
        lista.remove(number);
    }
    

    当然,您需要在删除或显示之前检查列表大小以避免异常。

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 2014-11-06
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      相关资源
      最近更新 更多