如何从一个数组中减去一些元素(元素)已经在另一个数组中?

How do I subtract some elements from one array which (element) are already in another array?

我有两个不同的数组,它们都包含相同类型的元素。这些元素是从用户输入中获得的。数组可以存储固定大小的元素。

*假设 第一个 基本上是一个 arrayList,它将用户输入添加到列表中。 second one 只是一个数组,它也从用户输入中获取值。第二个数组的所有元素也包含在第一个数组中并且这个数组的长度小于第一个数组*

现在我想打印一个数组,它是第一个数组-第二个数组.

的结果

这是我现在正在处理的程序。你可以避免这种编码只是为了给我一个这样做的理论概念。

    package issuetracking;

import java.util.*;

public class IssueTrackingObject {

    ArrayList<String> crIss = new ArrayList<String>();

    Scanner input = new Scanner(System.in);
    boolean crIss_bool;
    int numOfSolvedIss;
    private String[] solvedIss;

    //lets user create some issues and add them into an arrayList
    public void createIssue() {
        System.out.println("Enter 5 issues: ");

        for (int i = 0; i < 5; i++) {
            System.out.println("Issue " + (i + 1 + ": "));
            crIss_bool = crIss.add(input.nextLine());
        }

    }
//Let user mark some issues as solved (which are already in the list that the user has just created)

    public void solvedIssue() {
        System.out.println("How many solved issue you have(Must be less than 5): ");
        numOfSolvedIss = input.nextInt();

        solvedIss = new String[numOfSolvedIss];

        for (int k = 0; k < numOfSolvedIss; k++) {
            System.out.print("Enter solved issue(REMEMBER THAT THE SOLVED ISSUE MUST BE FROM ONE OF THEM YOU ALREADY HAVE CREATED)no. " + (k + 1) + ": ");

            solvedIss[k] = input.next();
        }

    }

    public void printUnsolvedIssue() {
        //print out the elements of createIssue() that doesn't belong to the solvedIssue()

    }

您可以使用如下简单的解决方案:

for (String solved : solvediss) {
    if (solved != null) crIss.remove(solved);
}

这将从数组中的列表中删除所有 String

当然你也可以这样做

crIss.removeAll(Arrays.asList(solvediss));

遍历第二个数组并使用 arraylist 中的 remove 方法从第一个数组中删除第二个数组的每个元素。

 for (int i = 0; i < solvedIss.length; i++) {
            crIss_bool = crIss.remove(solvedIss[i]);
 }

在这种情况下,删除元素可能是最简单的方法,但它会导致原始列表发生变化。

如果您不希望对原始列表进行任何破坏性修改,您可以执行如下简单的搜索。

for (String issue : crIss) {
    bool isUnSolved = true;
    for (String solvedIssue : solvedIss) {
        if (issue.equals(solvedIssue)) {
            isUnSolved = false;
            break;
        }
    }
    if (isUnSolved) {
        // Print the 'issue' or do whatever you want to do with it.
    }
}

希望对您有所帮助。
祝你好运。