You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写不影响其他集合的Set union方法?

Fixing the Union Method to Avoid Modifying Original Sets

The issue with your current union method is that it directly adds elements from the current set to the input set s, which modifies s permanently. A proper union operation should return a new set containing all elements from both original sets, leaving the original sets untouched.

Here's how to implement it correctly:

Step 1: Add Helper Methods to SetImp

First, we need a way to access elements from another SetImp instance without modifying it. Add these public helper methods to your SetImp class:

// Returns the number of elements in the set
public int getCount() {
    return count;
}

// Returns the element at the specified index (throws exception if index is invalid)
public int getElement(int index) {
    if (index < 0 || index >= count) {
        throw new IndexOutOfBoundsException("Index out of range: " + index);
    }
    return set[index];
}

Step 2: Rewrite the Union Method

Now, update the union method to create a new set, populate it with elements from both the current set and the input set, and return this new set:

public Set union(Set s){
    // Create a new SetImp instance to hold the union result
    SetImp unionSet = new SetImp();
    
    // Add all elements from the current set to the union set
    for(int i=0; i<count; i++){
        unionSet.add(set[i]);
    }
    
    // Add all elements from the input set s to the union set
    // Ensure s is an instance of SetImp before casting
    if (s instanceof SetImp) {
        SetImp sImp = (SetImp) s;
        for(int i=0; i<sImp.getCount(); i++){
            unionSet.add(sImp.getElement(i));
        }
    }
    
    return unionSet;
}

Why This Works

  • No modification to original sets: We create a brand new SetImp instance for the union result, so neither the current set nor the input set s are altered.
  • Proper union logic: The new set includes all unique elements from both original sets (thanks to the add method checking for duplicates via contains).

Example Usage

public static void main(String[] args) {
    SetImp set1 = new SetImp();
    set1.add(1);
    set1.add(2);
    
    SetImp set2 = new SetImp();
    set2.add(2);
    set2.add(3);
    
    Set unionResult = set1.union(set2);
    
    set1.display(); // Output: 1 2 (unchanged)
    set2.display(); // Output: 2 3 (unchanged)
    unionResult.display(); // Output: 1 2 3 (correct union)
}

内容的提问来源于stack exchange,提问作者ChingPoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:42:35