You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中ArrayList如何访问另一个类的方法以统计已更新站点数量

解决方案

核心修改点

  • 待调用的markAsUpdated方法当前为private私有修饰,仅允许所属类内部访问,需要调整为public公开修饰,其他类才能正常调用
  • 需要给站点类新增公开的状态查询方法,读取私有属性needsUpdate的状态,用于遍历统计
  • 确保存储站点的ArrayList指定了正确的泛型为站点类,避免类型转换问题

代码修改示例

站点类(包含markAsUpdated方法的类)

public class WebSite {
    // 原有私有属性
    private boolean needsUpdate = false;

    // 将private改为public,允许外部类调用标记更新
    public void markAsUpdated() {
        this.needsUpdate = true;
    }

    // 新增公开的状态查询方法
    public boolean isNeedsUpdate() {
        return this.needsUpdate;
    }
}

持有ArrayList的类的统计方法修改

// 先确保ArrayList定义时指定了泛型,示例:
// private List<WebSite> webSite = new ArrayList<>();

public int getNumberOfUpdatedSites() {
    int updatedCount = 0;
    for (int i = 0; i < webSite.size(); i++) {
        WebSite currentSite = webSite.get(i);
        // 调用站点类的公开方法判断状态
        if (currentSite.isNeedsUpdate()) {
            updatedCount++;
        }
    }
    return updatedCount;
}

其他可选优化(Java 8+适用)

可以用Stream API简化统计逻辑:

public int getNumberOfUpdatedSites() {
    return (int) webSite.stream()
            .filter(WebSite::isNeedsUpdate)
            .count();
}

扩展调用说明

如果要从持有ArrayList的类中调用站点的markAsUpdated方法,直接获取对应位置的站点对象调用即可:

// 示例:标记第2个站点为已更新(下标从0开始)
webSite.get(1).markAsUpdated();

内容的提问来源于stack exchange,提问作者GluhaiaMuha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:54:04