Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By jim829

Thread: Why does this work?

  1. #1
    Icandoit is offline Member
    Join Date
    Oct 2013
    Posts
    12
    Rep Power
    0

    Default Why does this work?

    Java Code:
    	public static void main(String args[]) {
    		Object[] o = {"hello", 5, "YOLO", "will this shuffle", "why does this shuffle?", "hello!"};
    		Collections.shuffle(Arrays.asList(o));
    		for(Object object : o) {
    			System.out.println(object);
    		}
    	}
    It prints it out shuffled... I don't know why it works though...

    My first thought was that I'd convert it to a list, shuffle it, and then convert it back to an array. Why does shuffling the new list returned by Arrays.asList change the original array?
    Last edited by Icandoit; 03-18-2014 at 01:22 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,616
    Rep Power
    5

    Default Re: Why does this work?

    Because asList returns an ArrayList. Arrays.asList(o) creates a new ArrayList and simply uses the supplied array as the array which backs up the ArrayList. So any changes to the ArrayList will also affect the original supplied array. The first sentence of the Arrays.asList documentation says
    "Returns a fixed-size list backed by the specified array."

    Regards,
    Jim
    kjkrum likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. Replies: 2
    Last Post: 11-25-2012, 02:51 AM
  2. Why. Does. This. Not. Work.
    By Kaytes in forum New To Java
    Replies: 1
    Last Post: 04-06-2012, 07:50 PM
  3. applet call dll work in Win2000 but not work in WinXP
    By manhcuongtin4 in forum Java Applets
    Replies: 1
    Last Post: 07-14-2011, 01:45 PM
  4. how would i get this to work...?
    By deeadeed in forum New To Java
    Replies: 6
    Last Post: 12-06-2007, 02:58 AM

Posting Permissions

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