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
    Rep Power

    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!"};
    		for(Object object : o) {
    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 02:22 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    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."

    kjkrum likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 2
    Last Post: 11-25-2012, 03:51 AM
  2. Why. Does. This. Not. Work.
    By Kaytes in forum New To Java
    Replies: 1
    Last Post: 04-06-2012, 08: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, 02:45 PM
  4. how would i get this to work...?
    By deeadeed in forum New To Java
    Replies: 6
    Last Post: 12-06-2007, 03: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