Question on LAB-1016 Java Collections accessing MyOwnClass in "For Your Own Excercise and Homework

49 views
Skip to first unread message

Jeff Aubert

unread,
Jul 14, 2016, 2:24:38 PM7/14/16
to JPassion.com: Java Programming
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
 

Jeff Aubert

unread,
Jul 21, 2016, 3:57:51 PM7/21/16
to JPassion.com: Java Programming
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
Reply all
Reply to author
Forward
0 new messages