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

Java集合框架练习:实现City类双向连通与间接连通判断功能

Java城市连通类实现方案

现有代码问题分析

你当前的代码存在三个核心问题:

  • connect方法仅实现单向连接,没有将当前城市同步添加到目标城市的连接集合中
  • isConnected方法仅判断直接连接关系,没有实现间接连通的遍历逻辑
  • 未重写toString方法,打印城市对象时无法直接输出城市名称

修正后的完整实现

import java.util.*;

public class City {
    private String name;
    private Set<City> connections;

    public City(String name){
        this.name = name;
        connections = new HashSet<>();
    }

    // 双向连接实现
    public void connect(City city){
        // 避免自连接和重复连接
        if (this == city || connections.contains(city)) {
            return;
        }
        connections.add(city);
        city.connections.add(this);
    }

    public Collection<City> getConnections(){
        // 返回副本避免外部修改内部集合
        return new HashSet<>(connections);
    }

    // 连通性判断(BFS实现,支持间接连通)
    public boolean isConnected(City city){
        // 自身默认连通
        if (this == city) {
            return true;
        }
        Set<City> visited = new HashSet<>();
        Queue<City> queue = new LinkedList<>();
        queue.add(this);
        visited.add(this);

        while (!queue.isEmpty()) {
            City current = queue.poll();
            for (City neighbor : current.getConnections()) {
                if (neighbor.equals(city)) {
                    return true;
                }
                if (!visited.contains(neighbor)) {
                    visited.add(neighbor);
                    queue.add(neighbor);
                }
            }
        }
        return false;
    }

    @Override
    public String toString() {
        return name;
    }

    // 可选:如果需要支持不同实例、同名城市视为同一个城市,可重写equals和hashCode
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        City city = (City) o;
        return Objects.equals(name, city.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    public static void main(String[] args) {
        City n = new City("Napoli"), r = new City("Roma"), s = new City("Salerno"), p = new City("Parigi");
        n.connect(s);
        n.connect(r);
        Collection<City> r_conn = r.getConnections();
        System.out.println(r_conn); // 输出 [Napoli]
        System.out.println(r.isConnected(s)); // 输出 true
        System.out.println(r.isConnected(p)); // 输出 false
    }
}

关键逻辑说明

  • 双向连接:调用connect方法时,同时在当前城市和目标城市的连接集合中添加对方,保证连接关系是双向的
  • 连通性判断:采用广度优先搜索(BFS)遍历所有连通的城市,用visited集合记录已经访问过的城市避免循环遍历,只要遍历到目标城市就返回true,遍历完所有连通节点未找到则返回false
  • 安全性优化:getConnections返回内部集合的副本,避免外部代码直接修改城市的连接关系

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:09:02