简体   繁体   中英

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

So, I have been given HashSet.java Code prepared by my professor. I have to use that and create a Union Method.

My Tester method includes some of the code like this.

    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);

So, now when I call my union method it does not return the Set_C HashSet.

This is my Union Method. I don't know how to fix it. Please help me and provide advice as to how I can get this to work.

Also How Do I "add each member of the set to the new union set", in this case 'temp'?

   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;
   } 

By convention, Java variable names use the camel case format. It is recommended that you use it too. For example you variable Biter should be bIter, the HashSet Set_C should be setC and so on.

Also a collection of objects can be traversed without explicitly creating the iterator. Let's suppose your HashSet contains Strings. Then the following loop can be used

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

Now to your question: Your Union method creates a new HashSet (temp) and adds the elements of the parameter HashSet (s1) to it, however, it never adds the current HashSet's (this) objects to temp!

Add this line after the temp.add(s1) line:

temp.add(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM