Help for loop question~~~Java


  • 0
    X

    Hey guys, I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and print every element, it shows they are still 0s.

                for(int num:a) 
                      num=1;
    

    But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try fails?

                for(int num=0;num<a.length;num++) 
                    a[num]=1;
    	        for(int n:a)
    	            System.out.println(n);

  • 0
    E

    I think the reason is that num is a primitive, so in your for loop you are modifying num only but not the object a. If num is an object, it would work as you expected. See the following example:

    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	list.add(Arrays.asList(1,2,3));
    	list.add(Arrays.asList(4,5,6));
    	list.add(Arrays.asList(7,8,9));
    	
    	// print current list:
    	System.out.println("Current: ");
    	for(List<Integer> l : list) {
    		for(Integer i : l)	
    			System.out.print(i + "\t");
    		System.out.println();
    	}
        /* output:
        Current: 
        1	2	3	
        4	5	6	
        7	8	9	
        */
    	
    	// update first element of every innerlist:
    	for(List<Integer> l : list) {
    		l.set(0, 1000);
    	}
    	
    	// print new list:
    	System.out.println("\nNew: ");
    	for(List<Integer> l : list) {
    		for(Integer i : l)	
    			System.out.print(i + "\t");
    		System.out.println();
    	}
        /* output:
        New: 
        1000	2	3	
        1000	5	6	
        1000	8	9	
        */

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.