在toString方法返回的ArrayList,当排列列表重演 [英] Permutations list repeating itself when returning ArrayList in toString method

查看:188
本文介绍了在toString方法返回的ArrayList,当排列列表重演的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*解决的:未清理出的ArrayList ebwteen调用,因此列表保持递增。我加perm.clear()的第二个循环中nextPermutation()之前,而问题就解决了​​!感谢所有谁帮助。

*SOLVED: Wasn't clearing out the ArrayList ebwteen calls, so the list kept incrementing. I added perm.clear() before the 2nd for loop in nextPermutation(), and problem solved! Thanks to all who helped.

我有在一个toString方法返回一个ArrayList的麻烦。我的任务是生成从数的1-10置换10列出。该方法nextPermutation称为10倍,在驱动

I'm having trouble returning an ArrayList within a toString method. My assignment is to generate 10 lists of permutations from the number 1-10. The method nextPermutation is called 10 times in the driver.

我希望我的输出是这样的:

I want my output to look like this:

List 1: [4 6 8 1 9 7 10 5 3 2]
List 2: [6 8 1 7 3 4 9 10 5 2]

等。

相反,每一个新的列表保存从最后一个列表排列,同时增加了新的置换,所以我得到这样的:

Instead, each new list keeps the permutation from the last list while adding a new permutation, so I get this:

List 1:  [6, 2, 3, 9, 4, 5, 10, 8, 7, 1]
List 2:  [6, 2, 3, 9, 4, 5, 10, 8, 7, 1, 3, 7, 2, 9, 1, 10, 6, 4, 8, 5]

下面是我的code:

import java.util.*;

public class PermutationGenerator {
    Random rand;
    ArrayList<Integer> perm = new ArrayList<Integer>();

    public PermutationGenerator(int s) {
        rand = new Random(s);
    }

    public void nextPermutation() {
        ArrayList<Integer> myArrayList = new ArrayList<Integer>();
        for (int i = 1; i <= 10; i++) {
            myArrayList.add(i);
        }

        for (int i = 1; i <= 10; i++) {
            int a = rand.nextInt(myArrayList.size());
            perm.add(myArrayList.get(a));
            myArrayList.remove(a);
        }
    }

    public final String toString() {
        return perm.toString();
    }
}

我能够改变无效nextPermutation()方法来ArrayList中,返回烫发方法内,并采取了从外地ArrayList和放置在nextPermutation方法来获得正确的输出。然而,对于任务,我需要nextPermutation为无效,我也需要一个toString方法。

I was able to get the correct output by changing the void nextPermutation() method to ArrayList, returning perm inside the method, and taking out the ArrayList from the field and placing it in the nextPermutation method. However, for the assignment I need nextPermutation to be void and I also need a toString method.

所以,我的问题是,我怎么回烫发内的toString,并得到一个排列每个列表?

So, my question is, how do I return perm within toString and get one permutation per list?

推荐答案

无论您需要在每次打印后,下一个呼叫 nextPermutation()之前清除烫发,或者有 nextPermutation()创建并返回其获取打印,然后扔掉的列表。

Either you need to clear perm each time after printing it and before the next call to nextPermutation(), or have nextPermutation() create and return a list which gets printed and then thrown away.

如果你不断增加的相同的列表,它只是要成长和壮大。

If you keep adding to the same list, it's just going to grow and grow.

这篇关于在toString方法返回的ArrayList,当排列列表重演的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆