Results 1 to 3 of 3
- 03-14-2008, 12:44 AM #1
Member
- Join Date
- Mar 2008
- Posts
- 2
- Rep Power
- 0
Question regarding foreach loop...
Hey everyone, I'm kind of stuck in this foreach loop. heres my code:
private Map<String, Person> record;
public Group()
{
record - new TreeMap<String, Person>();
}
public Group(Group group)
{
record = new TreeMap<String, Person>();
for (Person person : group.record)
{
this.record.put(person.getName(), person);
}
}
Now as I understand the foreach loop...
its taking all the elements that are in group.record and assigning them one by one to person. then im putting (person.getName(), and the actual object person into this.record.... however i keep getting the error "foreach not applicable to expression type" and its pointing at "group.record" in the foreach loop statement.
i am really stuck with this... can someone please help me!! thankyou so much in advance.
Shawn
- 03-14-2008, 03:21 AM #2
Java Code:import java.util.*; public class GroupTest { private Map<String, Person> record; public GroupTest() { record = new TreeMap<String, Person>(); } public GroupTest(GroupTest group) { record = new TreeMap<String, Person>(); // The for-each construct works like an Iterator. // The right argument in the for-each construct // should be an array or List. // What is group.record? System.out.println("group.record = " + group.record.getClass().getName()); // Try using the keySet. for (String key : group.record.keySet()) { Person person = group.record.get(key); this.record.put(key, person); } // An alternative. // record.putAll(group.record); } public static void main(String[] args) { String[] names = { "Sue", "John", "Linda" }; GroupTest test = new GroupTest(); for(String s : names) test.record.put(s, new Person(s)); System.out.println("test = " + test.record); GroupTest defensiveCopy = new GroupTest(test); System.out.println("defensiveCopy = " + defensiveCopy.record); } } class Person { String name; Person(String name) { this.name = name; } public String getName() { return name; } public String toString() { return "Person[name:" + name + "]"; } }
- 03-15-2008, 06:15 AM #3
Member
- Join Date
- Mar 2008
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
Question mark colon operator question
By orchid in forum Advanced JavaReplies: 9Last Post: 12-19-2010, 08:49 AM -
How to use do.. while loop
By -JaVa- in forum New To JavaReplies: 3Last Post: 08-30-2010, 08:52 PM -
How to use Foreach on an Array
By Java Tip in forum java.langReplies: 0Last Post: 04-16-2008, 11:06 PM -
foreach in jstl to display nested colums-struts jsp
By adil7 in forum JavaServer Pages (JSP) and JSTLReplies: 1Last Post: 02-11-2008, 06:19 AM -
While loop
By leebee in forum New To JavaReplies: 1Last Post: 07-18-2007, 03:11 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks