有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中创建数据类型时,构建构造函数以创建两个不同数组作为每个实例的一部分的最佳方法是什么?

这是我正在做的一个算法课程项目:

任务是构建一个数据类型,表示宇宙中的传统数学集。操作数据类型所包含的方法包括并集、交集等,它们需要在类/数据类型的两个实例之间进行比较。本课程希望我通过创建一个布尔数组来表示实际集合,这非常简单,如果您获取实际集合的数组,将其复制到相同长度的布尔数组,并根据集合中存在的值切换为true或false。以下是我得出的结论:

public class MathSET{

    private int size = 0;
    private Boolean[] currentSet;
    private Character[] universe;

    public MathSET(Character[] uni){
        if (uni.length == 0){
            System.out.println("Set cannot be created, universe cannot be null.");
        } else{
            universe = createUni(uni);
            currentSet = new Boolean[universe.length];
                for (int i = 0; i < universe.length; i++){
                    currentSet[i] = false;
                }
            }
    }

createUni产生了一个方法,该方法在返回universe数组之前对数组进行排序、删除重复项并调整大小,currentSet被创建为一个布尔数组,所有值都设置为“false”

我最大的问题是,我无法调用complete方法,该方法应该返回一个新的MathSET实例,其值不包括在当前集合中。我可以用表示补码的正确值创建一个数组,但不能用相同的通用数组创建一个新的数学集(布尔数组)。我还发现,当比较两个数据类型实例的universe数组以确保它们实际上是可比较的时,比较(comparable.universe!=this.universe)总是会得出两个数组不相等且无法比较的结果

我知道问题出在我的构造函数的某个地方,可能是变量的性质,但我很难看到它是什么。为了进一步澄清,我已经确认createUni方法确实使用正确的值创建了一个排序数组,并删除了重复项,并且当并排打印时,应该包含相同通用数组值的两个不同的MathSET实例在打印中是相等的,而不是比较

编辑:因为有人要求补足法:

public MathSET complement(){
    /**Creates a new MathSET boolean array that starts out empty, iterates through current MathSET currentSET array and adds 
    */
    MathSET complement = new MathSET(universe);
    StringBuilder comp = new StringBuilder("Complement to current set: ");
    for (int i = 0; i < currentSet.length; i++){
        if (this.currentSet[i] == false){
            complement.currentSet[i] = true;
            comp.append(complement.currentSet[i] + ", ");
        }
    }

    System.out.println(comp);
    return complement;
}

共 (0) 个答案