Results 1 to 4 of 4
  1. #1
    terahawks is offline Member
    Join Date
    Apr 2010
    Posts
    10
    Rep Power
    0

    Default 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

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    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.

  3. #3
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    Quote Originally Posted by masijade View Post
    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.
    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.

  4. #4
    terahawks is offline Member
    Join Date
    Apr 2010
    Posts
    10
    Rep Power
    0

Similar Threads

  1. Enhanced for loop in java
    By elizas in forum Java 2D
    Replies: 4
    Last Post: 03-29-2010, 05:43 PM
  2. Help for Enhanced for loop
    By jboy in forum New To Java
    Replies: 6
    Last Post: 09-13-2009, 06:45 AM
  3. Enhanced for loop
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-03-2007, 09:24 PM
  4. Enhanced For loop In Java
    By goldhouse in forum Advanced Java
    Replies: 1
    Last Post: 05-06-2007, 04:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •