在Java中有一个抽象类的List,并且需要遍历List



我正在尝试将我的代码从c#移到java,这是我第一次尝试编写java代码。

首先,我注意到c#中的list <>不像java中的list,我不得不使用arrayList,所以我只是改变了

List<Instruments> instruments = new List<Instruments>();

List<Instruments> instruments = new ArrayList<Instruments>(); 

那就解决了

稍后在我的程序中,我有一个for循环,它运行通过列表(一个抽象的"仪器"类),并比较枚举(保存在.type)值,所有子类都有。我:E

public static int HowManyOfType(InstrumentType TP)
{
    int HowMany = 0;
    for (int i = 0; i < instruments.Size(); i++)
    {
        if (instruments[i].type == TP)
        HowMany++;
    }
    return HowMany;
}

然而,我得到的消息"数组类型预期"。这个问题在c#中不会发生,因为属性存储在抽象类中,它只需要进行比较,而不需要知道所存储的子类的类型。我猜在java中并没有那么简单。这有什么问题吗?由于

修改

 if (instruments[i].type == TP) 

 if (instruments.get(i).type == TP)

把你的for循环改成这样

for (Instruments eachInstrument : instruments) {
    if (eachInstrument.type == TP) {
        howMany++;
    }
}

虽然不知道eachInstrument.type的数据类型是什么,但我不能确定使用==是正确的。您可能需要将其更改为eachInstrument.type.equals(TP)

如果你习惯使用c#,你可能会发现Java 8中的lambdas更自然。

long howMany = instruments.stream().filter(t -> t.type == TP).count();

除非类型是基本类型或Enum,否则可能需要使用equals

long howMany = instruments.stream().filter(t -> t.type.equals(TP)).count();

最新更新