变量分配和更改分配的对象

时间:2015-03-13 13:44:03

标签: java list allocation

findCycle()是关于找到一个不使用Streetsection的Loop。现在,如果我做nextStreetSection.setMarked(),它是否是StreetSection 被标记的currentPlace还是只是局部变量nextStreetSection?如果它只是局部变量,那么streetSections List of Place根本不会改变,标记不会改变。另一方面 setMarked()指的是nextStreetSection,为什么它会影响currentPlace中的List。

对于长代码,我很抱歉,我想确保上下文清晰。 我也是新来的:) 谢谢。

public Cycle findCycle(Place start)
{
    Cycle cycle = new Cycle();
    Place currentPlace = start;
    boolean done = false;
    if (start.getUnmarkedStreetSection() == null)
    {
        cycle.addPlace(start);
        done = true;
    }
    while (!done)
    {
        cycle.addPlace(currentPlace);
        StreetSection nextStreetSection = currentPlace.getUnmarkedStreetSection();
        nextStreetSection.setMarked();
        currentPlace = nextStreetSection.getOtherEnd(currentPlace);
        done = (currentPlace == start);
    }
    return cycle;
}


public StreetSection getUnmarkedStreetSection()
{
    for (StreetSection streetSection : streetSections)
    {
        if (!streetSection.isMarked())
            return streetSection;
    }
    return null;
}


public class StreetSection
{
    private Place place1, place2;
    private boolean marked;
    public StreetSection(Place place1, Place place2)
    {
        this.place1 = place1;
        this.place2 = place2;
        this.marked = false;
    }
}


public class Place
{
    private String name;
    private LinkedList<StreetSection> streetSections;

    public Place(String name)
    {
        this.name = name;
        this.streetSections = new LinkedList<StreetSection>();
    }
}

1 个答案:

答案 0 :(得分:0)

StreetSection链接当前Place和标记的下一个Place

因此,这会影响在Place中拥有此StreetSection的所有LinkedList<StreetSection> streetSections个对象。