ArrayList.contains()没有为某些值正确注册

时间:2015-01-29 14:56:13

标签: java arraylist

基本上,我有一个程序,它接受一个字符串并找到该字符串的所有唯一排列。为了检查重复项,我在评估时将排列添加到arraylist,然后使用arraylist.contains()检查每个排列。出于某种原因,它只适用于某些值,但完全忽略了一些重复项。这是我的代码:

import java.util.ArrayList;
public class Test
{
    private static int i;
    private static ArrayList<String> array;
    private static String temp;
    public static void main(String[] args)
    {
        array = new ArrayList<String>();
        Permutation generator = new Permutation("tweet");
        while(generator.hasMorePermutations())
        {
            temp = generator.nextPermutation();
            if(array.contains(temp))
            {

            }
            else
            {
            array.add(generator.nextPermutation());
            System.out.println(generator.nextPermutation());
            i++;
            }
        }
        System.out.println(i);
    }
}

这个类调用另一个创建排列的类的方法,其他类没有问题。

此代码的输出是36个排列,而不是30.当读取终端时,很明显有重复。

2 个答案:

答案 0 :(得分:3)

您拨打generator.nextPermutation()两次,而不是将temp插入数组列表

    while(generator.hasMorePermutations())
    {
        // get a permutation
        temp = generator.nextPermutation();
        // test for contains
        if(array.contains(temp))
        {

        }
        else
        {
            // insert a new permutation instead of temp
            array.add(generator.nextPermutation());
            // print yet another new permutation instead of temp
            System.out.println(generator.nextPermutation());
            i++;
        }

只需确保您执行array.add(temp)而不是array.add(generator.nextPermutation())

警告:除非你的排列生成器有一个奇怪的界面,当你调用hasMorePermutations时它只会移动到下一个排列,在这种情况下我不知道它为什么不起作用!< / em>的

答案 1 :(得分:0)

您正在拨打nextPermutation()三次而不是一次。您应该使用array.add(temp)System.out.println(temp);代替。