有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Arraylist中查找具有多个属性的对象?

我有一个类,其构造函数如下所示:

public Stock(String symbol, String name, int value) {
    this.symbol = symbol;
    this.name = name;
    this.value = value;
}

现在,我有了另一个抽象数据类型的类:

public class Holding {
    private Stock stock;
    private int amount;

    public Holding() {
        this.stock = null;
        this.amount = 0;
    }

    public Holding(Stock stock, int amount) {
        this.stock = stock;
        this.amount = amount;
    }
}

现在,我正在另一个类中编写一个方法

我已经使用上面的Holding类创建了一个arraylist。 在这个班

private ArrayList<Holding> holdings;

现在,我知道Holding类中的对象包含一个stock对象和一个int-amount

如何仅访问HoldingArrayList中我的stock对象中的符号


共 (3) 个答案

  1. # 1 楼答案

    How can I access only the symbol in my stock object in the Holding ArrayList?

    使用给定的代码,您无法执行此操作

    • 您需要为Holding类的stock字段添加公共getter方法
    • 您(可能)需要为Stock类的symbol字段添加公共getter方法

    完成后,您可以执行以下操作:

    public Holding getHoldingForSymbol(List<Holding> holdings, String symbol) {
        for (Holding h : holdings) {
            if (h.getStock().getSymbol().equals(symbol)) {
                return h;
            }
        }
        return null;  // or throw an exception
    }
    
  2. # 2 楼答案

    您可能希望使用Java的foreach循环遍历ArrayList:

    for (Holding currentHolding : holdings) {
      System.out.println(currentHolding.stock.symbol); // prints out all the symbols
    }
    

    您需要将属性Stock从private更改为public,或者创建一个getStock方法来返回它。否则,因为它是私有的,所以您无法访问它

  3. # 3 楼答案

    不知道你的意思

    for (Holding h : holdings) {
        out.println(h.getStock().getSymbol());
    }
    

    这是假设你有合适的获得者