![](/img/trans.png)
[英]How do I pass an object as a parameter to a method without affecting the object?
[英]How do I write a union method without affecting the other sets?
這是界面
public interface Set{
public static final int MAX=10;
public void add(int e);
public Set union(Set s);
public void display();
}
設置Imp
public class SetImp implements Set{
private int[] set;
private int count;
public SetImp(){
set = new int[MAX];
count = 0;
}
public void add(int e){
if(!contains(e))
set[count++]=e;
}
private boolean contains(int e){
boolean found=false;
for(int i=0;i<count;i++){
if(set[i]==e){
found=true;
break;
}
}
return found;
}
public void display(){
for(int i=0;i<count;i++)
System.out.print(set[i] + " ");
System.out.println();
}
我遇到最多問題的地方。 每當我嘗試將 Set 與 set 結合時,聯合都會在兩個 s 中生效。 我嘗試制作一個臨時變量,但它仍然不起作用。
public Set union(Set s){
for(int i=0; i<count; i++){
s.add(set[i]);
}
return s;
}
}
您的代碼以 2 組開頭:
給定set1.union(set2)
,當然有 set1 和 set2 。
給定: Set set3 = set1.union(set2);
有 3 個完全獨立的集合:set1 和 set2 沒有變化,這意味着 set3 不同。
因此,您必須擁有 3 套。 鑒於在union
方法的開頭只有 2... 這意味着您必須在某個地方調用new SetImp()
,否則這將永遠無法解決。
我敢肯定,有了這個提示,您就可以解決這個問題:)
創建一個新的SetImp
並將兩個Set
添加到它。
public Set union(Set s){
final Set res = new SetImp();
for(int i = 0; i < count; i++){
res.add(set[i]);
}
for(int i = 0; i < s.count; i++){
res.add(s.set[i]);
}
return res;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.