Results 1 to 4 of 4
Thread: Enhanced For Loop
- 04-14-2010, 02:28 PM #1
Member
- Join Date
- Apr 2010
- Posts
- 10
- Rep Power
- 0
Enhanced For Loop
Hi,
To begin with, am pretty new to this enhanced for loop concept. Tried first few hands on it and found it pretty cool. I have a doubt regarding the enhanced for loop. The doubt is that what if we am using array of class type the in that case can i use enhanced for loop? if yes then how? or is enhanced for loop restricted to primitive type?
Thank you
- 04-14-2010, 02:48 PM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,568
- Rep Power
- 15
Seeing as you declare the type to be "extracted" on the left hand side of the ":", I would have to assume, from that alone, that it will work for any type.
- 04-14-2010, 03:03 PM #3
i have a piece of code that show this
Java Code:public class TestClass { private int i; public int getI() { return i; } public TestClass(int i) { this.i = i; } public static void main(String[] args) { TestClass[] t = new TestClass[2]; t[0] = new TestClass(1); t[1] = new TestClass(2); for (TestClass c : t) { System.out.println(c.getI()); } } }
the problem here is if the TestClass is declared with more elements and these are not filled then the loop will cause a NullPointerException. but the purpose of the code above is to show a loop through a collection that contains not primitives but objects. and in real life there are better collections then arrays to use.
- 04-16-2010, 09:46 AM #4
Member
- Join Date
- Apr 2010
- Posts
- 10
- Rep Power
- 0
Similar Threads
-
Enhanced for loop in java
By elizas in forum Java 2DReplies: 4Last Post: 03-29-2010, 06:43 PM -
Help for Enhanced for loop
By jboy in forum New To JavaReplies: 6Last Post: 09-13-2009, 07:45 AM -
Enhanced for loop
By Java Tip in forum Java TipReplies: 0Last Post: 11-03-2007, 10:24 PM -
Enhanced For loop In Java
By goldhouse in forum Advanced JavaReplies: 1Last Post: 05-06-2007, 05:26 PM
Bookmarks