ArrayList在递归方法中的行为

时间:2018-04-25 12:47:57

标签: java recursion arraylist reference

我有一个向量的ArrayList,我试图找到所有可能的不同路径(不重复相同的节点)。但ArrayList保留路径记录似乎是共享的,因此泄漏所有路径。我的问题是,是否有一个替代列表类型,我应该使用哪个阻止这个?感谢。

可用路径是(A-> B,B-> C,C-> D,D-> A,A-> C)

首先,我决定只处理起始节点A的路径。

输出应为:
ABCD
ACD

我已经使用其他输出编写了下面的代码,以检查正在进行的操作,因为它无法正常工作。以下代码的输出是:

上一个矢量:SA
矢量历史大小:1
下一个矢量:AB
上一个矢量:AB
矢量历史大小:2
下一个载体:BC
上一个载体:BC
矢量历史大小:3
下一个载体:CD
上一个载体:CD
矢量历史大小:4
下一个矢量:DA
循环 - ABCDA
ABCDA
ABC
AB
矢量历史大小:4
下一个矢量:AC
循环 - AC
AC

正如您所看到的,while循环的第二次迭代中的最后4行是错误的,因为向量历史记录大小应该是1(仅SA)和" C"之前不应该访问过,但不知何故,来自第一个while循环递归的向量历史的ArrayList已经泄露了。是否会发生这种情况以及有哪些替代方案?

public static void main(String[] args) {

    ArrayList<vector> vectorList = new ArrayList();
    vectorList.add(new vector("A", "B"));
    vectorList.add(new vector("B", "C"));
    vectorList.add(new vector("C", "D"));
    vectorList.add(new vector("D", "A"));
    vectorList.add(new vector("A", "C"));

    //to record vector history and initialize the start vector
    ArrayList<vector> vectorHistory = new ArrayList();

    //record the path 
    String path = "";

    //method call
    pathFinder(new vector("S", "A"), vectorHistory, vectorList, path);
}

//Recursive method. moves one node forward until there is no more nodes OR the next node is the same as a previously taken node

public static void pathFinder(vector prevVector, ArrayList<vector>  vectorHistory, ArrayList<vector> vectorList, String path) {

    vectorHistory.add(prevVector);

    //add the current node to the path
    path = path + prevVector.child;
    System.out.println("Previous vector: "+ prevVector.parent+prevVector.child);

    // search if there is a next node.  looped to search all possible paths
    while (vectorList.contains(prevVector)) {
        System.out.println("vector history size: "+ vectorHistory.size());

        //retrieve the next vector
        vector nextVector = vectorList.get(vectorList.indexOf(prevVector));
        System.out.println("Next vector: " + nextVector.parent + nextVector.child);

        //remove current node so while loop can move to another possible path
        vectorList.remove(vectorList.indexOf(prevVector));

        //check if the next node has already been visited before
        if (vectorHistory.contains(nextVector)) {
            path=path+nextVector.child;
            System.out.println("Looped - " + path);


        } else {
            pathFinder(nextVector, vectorHistory, vectorList, path);
        }
    }

    System.out.println(path);

}

/*object vector */  
public static class vector {
    String parent, child;

    public vector(String parent, String child) {
        this.parent = parent;
        this.child = child;

    }

    @Override
    public boolean equals(Object o) {

        vector x = (vector) o;
        if (x.parent.equalsIgnoreCase(child)) {
            return true;
        } else {
            return false;
        }
    }

}

1 个答案:

答案 0 :(得分:2)

Java是&#34;传递价值&#34;所以它传递了实际对象的引用的副本。但是在使用集合时理解它有点奇怪,因为发送的引用副本指向与原始集合相同的内存!

因此,如果将列表传递给方法并修改列表中的方法,则会修改原始列表。

例如:

method b(List aList){
  aList.add(new Object());
}

method c(List aList){
  aList=new ArrayList ();
  aList.add(new Object());
}


List a=new ArrayList();
b(a); -> it will add an object to a;
c(a); -> it will not add an object to a or modify it in any way

所以在你打电话的情况下 pathFinder(nextVector, vectorHistory, vectorList, path);你没有得到那个&#34; stack&#34;您希望通过递归的行为,因为路径查找器的后继调用会修改先前的列表。

你可以像这样修改你的电话:

pathFinder(nextVector, new ArrayList<>(vectorHistory), new ArrayList<>(vectorList), path);

为了避免这个问题,但每次都会丢失一些额外的内存复制整个列表;)并且它仍然无法获得你想要的结果,因为我猜你在算法中有另一个错误。

你的程序看起来很奇怪;)你用矢量相等的魔法并不好,因为你实际上无法比较两个相等的物体。例如,您的代码AB与AB不同(事实并非如此)。因此,对于你曾经去过的地方,你不需要向量而是积分。所以这里有一点修改过的程序只是为了说明我的意思。它还远非完美:

import java.util.ArrayList;
import java.util.List;

public class MainClass {
    public static void main(String[] args) {

        List<MyVector> vectorList = new ArrayList<MyVector>();
        vectorList.add(new MyVector("A", "B"));
        vectorList.add(new MyVector("B", "C"));
        vectorList.add(new MyVector("C", "D"));
        vectorList.add(new MyVector("D", "A"));
        vectorList.add(new MyVector("A", "C"));

        List<String> pointsHistory=new ArrayList<String>();
        //to record points that have been visited
        //record the path 
        String path = "";
        //method call
        pathFinder(new MyVector(null, "A"), pointsHistory, vectorList, path);
    }

    //Recursive method. moves one node forward until there is no more nodes OR the next node is the same as a previously taken node

    public static void pathFinder(MyVector prevVector, List<String>  pointsHistory, List<MyVector> vectorList, String path) {
        pointsHistory.add(prevVector.child);
        //add the current node to the path
        path = path + prevVector.child;
        // search if there is a next node.  looped to search all possible paths -> no need to do magic with equals
        for(MyVector vector:vectorList)
            if(vector.parent.equals(prevVector.child)) {
                  System.out.println("Next vector: " + vector.parent + vector.child);
                  if (pointsHistory.contains(vector.child)) {
                    System.out.println("Result " + path);  //You get the end result here -> if we have reached a loop
                } else {
                    pointsHistory.add(vector.child);
                     pathFinder(vector, new ArrayList<>(pointsHistory), vectorList, path);
                }
            }          
    }

    /*object vector */  
    public static class MyVector {
        String parent, child;

        public MyVector(String parent, String child) {
            this.parent = parent;
            this.child = child;
        }
    }
}

您将获得您想要的结果。看看我如何复制访问过的点:pathFinder(vector,new ArrayList&lt;&gt;(pointsHistory),vectorList,path);为了那项工作。请用大写字母命名你的课程。