簡體   English   中英

我的聯合方法不起作用,如何解決?

[英]My Union Method is not working, How can I fix it?

因此,教授給我提供了HashSet.java代碼。 我必須使用它並創建一個聯合方法。

我的Tester方法包括一些這樣的代碼。

    Set_B.add(1);

    Iterator Biter = Set_B.iterator();
    System.out.print("\nSet B: ");
    while(Biter.hasNext())
    {
        System.out.print(Biter.next() + " ");  
    }

    System.out.println();

    HashSet Set_C = Set_A.Union(Set_B);

    System.out.println("\nThe Union Set is: " + Set_C);

因此,現在當我調用我的聯合方法時,它不會返回Set_C HashSet。

這是我的聯合方法。 我不知道該如何解決。 請幫助我,並提供有關如何使它起作用的建議。

另外,如何“將集合的每個成員添加到新的聯合集合”(在這種情況下為“臨時”)?

   public HashSet Union(HashSet s1)
   {

   HashSet temp = new HashSet(101);//Creating a new HashSet     

   Iterator iter = s1.iterator();
   System.out.print("The Set passed is: ");
   while(iter.hasNext())
   {        
       System.out.print(iter.next());
   }

   temp.add(s1);

   return temp;
   } 

按照約定,Java變量名稱使用駝峰大小寫格式。 建議您也使用它。 例如,變量Biter應該是bIter,HashSet Set_C應該是setC,依此類推。

同樣,可以遍歷對象的集合,而無需顯式創建迭代器。 假設您的HashSet包含字符串。 然后可以使用以下循環

HashSet setC = new HashSet();
//add elements here
for(String oneElement: setC){
//do something
}

現在您的問題:您的Union方法創建一個新的HashSet(temp)並向其添加參數HashSet(s1)的元素,但是,它永遠不會將當前HashSet的(this)對象添加到temp!

在temp.add(s1)行之后添加以下行:

temp.add(this);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM