Everyone,

To iterate through these collections when adding a class object as a 
collection item, the answer was in some older postings in this group.

I followed the suggestion to Override the toString method within 
MyOwnClass  :

public String toString() { 

    return this.name + " Age : " +  (this.age) ;
  } 

 
So when assigning who class objects as in this code
 

HashSet hs = new HashSet(); 

hs.add("LSU");  // Sring objects
hs.add("Tigers");
MyOwnClass moc1 = new  MyOwnClass("Jeff", 55);     
MyOwnClass moc2 = new  MyOwnClass("Tom", 48); 
hs.add(moc1);

 hs.add(moc2);  
 
 Integer myInt1 = 100;
 Integer myInt2 = 50;
 Integer myInt3 = 25;
 hs.add(myInt1);  // Integer objects
 hs.add(myInt2);
 hs.add(myInt3);
 

the standard iteration worked 
 

System.out.println("Contents of Hash Set");
System.out.println();

for (Iterator i = hs.iterator(); i.hasNext();) {
      System.out.println(i.next());
    }

Example output 
 

50
Jeff Age : 55
100
Tom Age : 48
25
Tigers
LSU

 
To those posters from a few years ago, thank you.


Jeff

On Thursday, July 14, 2016 at 1:24:38 PM UTC-5, Jeff Aubert wrote:

> Everyone,
>
> When the instructions say to add 2 objects from MyOwnClass, am I loading 
> them individually like this ,
>
>
>    MyOwnClass moc1 = new  MyOwnClass("Jeff", 55);     // MyOwnClass 
> (String name, Int age); 
>     
>     hs.add(moc1.name); 
>     hs.add(moc1.age);
>
>
> or am I adding an object that is the whole class , such as 
>
>     MyOwnClass moc1 = new  MyOwnClass("Jeff", 55);     
>     MyOwnClass moc2 = new  MyOwnClass("Tom", 48); 
>     hs.add(moc1); 
>     hs.add(moc2);  
>
>
> If I am supposed to do the second option, i.e., add the instance of the 
> whole class as a collections item, then how do
> I correctly interatre through that hash set (or other collection)  ?  Do 
> I a conversion to a string when I print this ? 
>
> What are the recommendations for this situation ?
>
> Thank You and Regards,
>
> Jeff 
>  
>

-- 
You received this message because you are subscribed to the Google Groups 
"JPassion.com: Java Programming" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
Visit this group at https://groups.google.com/group/jpassion_java.
For more options, visit https://groups.google.com/d/optout.

Reply via email to