0

我正在尝试创建一个程序,该程序将搜索文件数组并将唯一文件名存储到新文件数组中并返回该新数组,只将重复项放入一次(如果有的话)。我的代码会运行,但不会将值存储到我创建的新文件数组中,该文件数组没有设定长度。当我调用它时,它只返回一个空数组。我设置它的方式是检查是否有任何重复项,如果有,则将重复项存储一次,如果没有,则仅存储值并继续。问题是一旦通过 for 循环,它就不会存储这些值。有没有更好的方法将值存储在文件数组中?

这是我的方法uniqueFile,它从我的测试块接收文件数组。

public static File[] getUnique(File[] files) {
    int count = 0, place = 0;
    File[] newFile = new File[] {};
    for (int i = 0; i < files.length; i++) {
        count = 0;
        for (int x = 1; x < files.length; x++) {
            if (files[i].equals(files[x]))
                count++;
        }
        try {
            if (count >= 1)
                newFile[place] = files[i];
            else
                newFile[place] = files[i];
        } catch (Exception e) {

        }
        place++;
    }

    return newFile;
}

这是我的测试块:

{
    File Freckle = new File("Freckle");
    File Pickle = new File("Pickle");
    File Sam = new File("Sam");
    File Cat = new File("Cat");
    File[] files = new File[] { Freckle, Pickle, Freckle, Sam, Cat,
            Pickle };

    File[] output = ArrayExercises.getUnique(files);
    System.out.println(Arrays.toString(output));
}

我输入了通用文件名来测试它是否有效。最终我将合并实际文件,但我想在继续之前先弄清楚这个错误。

4

2 回答 2

3

你让自己的事情变得非常困难。让 Java 为您完成所有工作。尝试使用 LinkedHashSet,因为它为您提供唯一性,同时保留插入顺序。它也比将每个值与其他值进行比较更有效。

File [] input = {Freckle, Pickle, Freckle, Sam, Cat, Pickle};
Set<File> tmp = new LinkedHashSet<File>();
for (File each : input) {
    tmp.add(each);
}
File [] unique = new File[tmp.size()];
int i = 0;
for (File each : tmp) {
    unique[i++] = each;
}
System.out.println(Arrays.toString(unique));
于 2013-02-20T06:42:55.367 回答
0

正如其他人所说,您应该使用 Java Collections API,它让生活变得如此轻松。但是,假设您想让您的解决方案发挥作用。

他的问题是你的新数组长度为零,这里有一段非常奇怪的代码。

     if (count >= 1)
            newFile[place] = files[i];
        else
            newFile[place] = files[i];

测试毫无意义,无论计数值如何,您都在做完全相同的事情。您还需要仅place在将非重复字符串添加到数组时增加。尝试/捕获也是毫无意义的。捕获通用异常是不好的做法。

你需要的更像下面,但即使这样也不会完全想要你想要的,尽管数组现在只包含唯一的条目,它的长度和以前一样。

public static File[] getUnique(File[] files) {
    place = 0;
    File[] newFile = new File[files.size()]; //you were creating an empty array.
    for (int i = 0; i < files.length; i++) {
        boolean duplicate = false; // not interested in ho many dupes, just if there is one. 
        for (int x = 1; x < files.length; x++) {
            if (files[i].equals(files[x])) {
                duplicate = true;
                break; // no point in checking the rest.
             }
        }
        //   why on earth did you have a try catch?
        if (!duplicate) {
            newFile[place++] = files[i];
         }

    }

    return newFile;
}

你真正需要做的就是把它扔掉,然后像LinkedHashMap另一张海报建议的那样重新开始使用,否则你会用低效的代码把自己绑起来。

于 2013-02-20T06:58:06.843 回答