Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

Arrays.asList() doesn't work quite like I would think it should

Thread view: 
Ken - 03 Oct 2007 04:24 GMT
I've included an example of the problem I've run into.  I'm trying to
randomize an array of integers, much like the following program does.
Unfortunately when I ask the system to do so, I don't get a randomized
array.  Now normally this wouldn't bother me.  I would just assume that
a new object is being created and then destroyed by the garbage collector
without my ever seeing it, but in this case it looks like a bug.  

Isn't the whole point of the asList() interface to allow this kind of
thing?

Is this a bug in Java?

Signature

Kenneth P. Turvey <kt-usenet@squeakydolphin.com>

--------------------------------------------------------------------

import java.util.Arrays;
import java.util.Collections;

public class ArrayAsListTester {

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {
       int indicies[] = new int[100];
       
       for (int index = 0; index < 100; index++) {
           indicies[index] = index;
       }
       
       Collections.shuffle(Arrays.asList(indicies));
       
       for (int index = 0; index < 100; index++) {
           System.out.println(indicies[index]);
       }
   }
}

Stefan Ram - 03 Oct 2007 05:08 GMT
 Writing your program in front of the signature separator
 will enhance the visibility of your code.

>int indicies[] = new int[100];

 Use »java.lang.Integer indicies[] = new java.lang.Integer[ 100 ];« here.

 Otherwise, »asList« will see an array with only one component
 »indicies« because its parameter has type »T...«.

 Using an English word like »indices« (instead of
 »indicies«) will enhance the readability of your code.
xen - 03 Oct 2007 05:11 GMT
>I've included an example of the problem I've run into.  I'm trying to
>randomize an array of integers, much like the following program does.
[quoted text clipped - 7 lines]
>
>Is this a bug in Java?

Arrays.asList() tries to instantiate an ArrayList on the specified
array but an ArrayList can never be backed by an int[].

If you call asList() on an int[], you will get a List<int[]> with one
element: the int[] you supplied. If you call shuffle on that list,
nothing will change in the int[].

You don't get an error because the parameter for asList is a "T... a".
If you call it with a T[], that array is passed.
If you call it with an array of a primitive type, then it cannot be
treated as a T[] because generic types cannot be primitives. Instead,
because int[] itself is an object, it matches the T in the signature
and is wrapped inside an array. So what actually gets passed is not
your int[], but an array of  int[] with one element.

There is no way for the compiler to generate an error.
And why should ArrayList(T... t) complain? An int[] is a valid type
parameter.

Perhaps the compiler should generate a warning if you pass an array of
primitive to a generic dynamic array parameter.

Anyway, you can only solve it by using an Integer[] instead of an
int[].
Mark Space - 03 Oct 2007 05:17 GMT
> I've included an example of the problem I've run into.  I'm trying to
> randomize an array of integers, much like the following program does.
[quoted text clipped - 7 lines]
>
> Is this a bug in Java?

I doubt it.  A more experienced Java programmer would spot this right away.

I didn't run your program (which is a shame since you did include a good
one), but I'm gonna guess that the output is a sorted, not randomized list.

Not a Java bug.

asList returns a NEW OBJECT.  Your original array was never touched. Try
something like:

List myList = Arrays.asList(indicess);
Collections.shuffle(myList);

Then print out myList and see what you get.
Stefan Ram - 03 Oct 2007 05:30 GMT
>asList returns a NEW OBJECT.  Your original array was never touched.

 In German, there is a saying »Wer schreit hat Unrecht.«¹. Thus,

     »Changes to the returned list "write through" to the array.«

http://download.java.net/jdk7/docs/api/java/util/Arrays.html#asList(T...)

 1) »He who shouts is wrong.«. In Usenet, using
    all caps sometimes is considered to resemble shouting.
Roedy Green - 03 Oct 2007 06:46 GMT
>      »Changes to the returned list "write through" to the array.«

That was a surprise.  I looked up Arrays.asList and there it was.

It also says .

This method also provides a convenient way to create a fixed-size list
initialized to contain several elements.

This means insert and delete would be suppressed.  Shuffle just might
try to use those methods.

I got caught because I always use these idioms:

ArrayList <=> array

// NEW STYLE with generics

// converting an array to an ArrayList, with Generics
String[] animals = { "bear", "cougar", "wolverine"};
ArrayList<String> al = new ArrayList<String>( Arrays.asList( animals )
);

// converting an ArrayList to an array with generics.
String[] predators = al.toArray( new String[ al.size() ] );

// OLD STYLE, without generics

// converting an array to an ArrayList, without Generics
String[] animals = { "bear", "cougar", "wolverine"};
ArrayList al = new ArrayList( Arrays.asList( animals ) );

// converting an ArrayList to an array without generics,
String[] predators = (String[])al.toArray( new String[ al.size() ] );
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Mark Space - 05 Oct 2007 08:01 GMT
>> asList returns a NEW OBJECT.  Your original array was never touched.
>
>   In German, there is a saying »Wer schreit hat Unrecht.«¹. Thus,
>
>       »Changes to the returned list "write through" to the array.«

That *is* surprising.  I assumed a deep copy.  It looks like it's
actually just a wrapper, and the "list" is implemented as the original
array.  Kinda cool.

> http://download.java.net/jdk7/docs/api/java/util/Arrays.html#asList(T...)
>
>   1) »He who shouts is wrong.«. In Usenet, using
>      all caps sometimes is considered to resemble shouting.

Yes, but I learned something.  "Squeaky wheel gets the grease." ;-)
Roedy Green - 03 Oct 2007 06:39 GMT
>    Collections.shuffle(Arrays.asList(indicies));

asList makes a copy.  So you have shuffled a new copy of the data in a
List then thrown it away. Your code does not shuffle the original
array.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Daniel Pitts - 03 Oct 2007 06:42 GMT
>>    Collections.shuffle(Arrays.asList(indicies));
>
> asList makes a copy.  So you have shuffled a new copy of the data in a
> List then thrown it away. Your code does not shuffle the original
> array.

Actually, it does *not* make a copy. It makes a List instance that
"wraps" the array.

The problem with the OP's code is the fact that you can't use
Arrays.asList on an array of primatives.

Many people have pointed this out, and have suggested that the OP use
Integer[] instead.  It is a pity that Sun didn't add an Arrays.shuffle
for the primitive array types.
Piotr Kobzda - 03 Oct 2007 08:24 GMT
> It is a pity that Sun didn't add an Arrays.shuffle
> for the primitive array types.

Maybe lack of boxing of primitive type arrays is bigger pity?

Hopefully, we can easily do something similar, see example below.

piotr

import java.util.*;

public class ArrayBoxingTest {

    public static void main(String[] args) {
        final int[] a = new int[] { 1, 2, 3, 4, 5 };
        Collections.shuffle(new AbstractList<Integer>() {

            public int size() { return a.length; }

            public Integer get(int index) { return a[index]; }

            public Integer set(int index, Integer element) {
                Integer r = a[index];
                a[index] = element;
                return r;
            }

        });
        System.out.println(Arrays.toString(a));
    }
}
Roedy Green - 03 Oct 2007 08:55 GMT
On Tue, 02 Oct 2007 22:42:24 -0700, Daniel Pitts
<newsgroup.spamfilter@virtualinfinity.net> wrote, quoted or indirectly
quoted someone who said :

>The problem with the OP's code is the fact that you can't use
>Arrays.asList on an array of primatives.
>
>Many people have pointed this out, and have suggested that the OP use
>Integer[] instead.  It is a pity that Sun didn't add an Arrays.shuffle
>for the primitive array types.

But you don't get any error message, just some VERY weird run-time
behaviour.  see http://mindprod.com/jgloss/array.html#GOTCHAS
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 03 Oct 2007 08:49 GMT
>        Collections.shuffle(Arrays.asList(indicies));

This code puzzled the heck out of me.

I have done experiments and I think I now know what is going on.  It
is far stranger than you would imagine.

I have posted my findings at
http://mindprod.com/jgloss/array.html#GOTCHAS

I think it fair to say OP DID find a bug in Java, or at least the
mother of all gotchas.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Ken - 03 Oct 2007 09:18 GMT
>>        Collections.shuffle(Arrays.asList(indicies));
>
> This code puzzled the heck out of me.

It did me too.  Thank all of you for your assistance in this matter.  I
understand the problem now.  I'm still a bit annoyed that there isn't a
straight forward way to shuffle an array of ints given that the code is
already there hidden somewhere, but at least I understand the problem now.  

Signature

Kenneth P. Turvey <kt-usenet@squeakydolphin.com>

Roedy Green - 03 Oct 2007 13:29 GMT
>It did me too.  Thank all of you for your assistance in this matter.  I
>understand the problem now.  I'm still a bit annoyed that there isn't a
>straight forward way to shuffle an array of ints given that the code is
>already there hidden somewhere, but at least I understand the problem now.  

Let's peek under the covers at java.util.Collections.shuffle.
Internally it converts to an array to shuffle!

/**
    * Randomly permute the specified list using the specified source
of
    * randomness.  All permutations occur with equal likelihood
    * assuming that the source of randomness is fair.<p>
    *
    * This implementation traverses the list backwards, from the last
element
    * up to the second, repeatedly swapping a randomly selected
element into
    * the "current position".  Elements are randomly selected from
the
    * portion of the list that runs from the first element to the
current
    * position, inclusive.<p>
    *
    * This method runs in linear time.  If the specified list does
not
    * implement the {@link RandomAccess} interface and is large, this
    * implementation dumps the specified list into an array before
shuffling
    * it, and dumps the shuffled array back into the list.  This
avoids the
    * quadratic behavior that would result from shuffling a
"sequential
    * access" list in place.
    *
    * @param  list the list to be shuffled.
    * @param  rnd the source of randomness to use to shuffle the
list.
    * @throws UnsupportedOperationException if the specified list or
its
    *         list-iterator does not support the <tt>set</tt>
operation.
    */
   public static void shuffle(List<?> list, Random rnd) {
       int size = list.size();
       if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess)
{
           for (int i=size; i>1; i--)
               swap(list, i-1, rnd.nextInt(i));
       } else {
           Object arr[] = list.toArray();

           // Shuffle array
           for (int i=size; i>1; i--)
               swap(arr, i-1, rnd.nextInt(i));

           // Dump array back into list
           ListIterator it = list.listIterator();
           for (int i=0; i<arr.length; i++) {
               it.next();
               it.set(arr[i]);
           }
       }
   }
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 03 Oct 2007 13:56 GMT
On Wed, 03 Oct 2007 12:29:52 GMT, Roedy Green
<see_website@mindprod.com.invalid> wrote, quoted or indirectly quoted
someone who said :

>Let's peek under the covers at java.util.Collections.shuffle.
>Internally it converts to an array to shuffle!

Here is the guts, that handles an int[]. Note how much simpler the
code is. You can download this as part of the common11 package
at http://mindprod.com/products.html#COMMON11

/**
* Shuffles an int[], much like Collections.shuffle
* copyright (c) 2007 Roedy Green, Canadian Mind Products Shareware
 that may be copied and used freely for any purpose but military.
 Roedy Green<
 Canadian Mind Products
 #101 - 2536 Wark Street
 Victoria, BC Canada
 V8T 4G8
 mailto:roedyg@mindprod.com
 http://mindprod.com
*/
package com.mindprod.common11;

import java.util.Random;

/**
* Shuffles an int[], much like Collections.shuffle
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0, 2007-10-03 Created with IntelliJ IDEA.
*/
public class Shuffle {

   // ------------------------------ FIELDS
------------------------------

   /**
    * true if you want the debugging main harness.
    */
   private static final boolean DEBUGGING = true;

   /**
    * default source of randomness for shuffling.
    */
   private static Random wheel;

   // -------------------------- PUBLIC STATIC METHODS
--------------------------

   /**
    * Works much like Collections.shuffle. Randomly permutes the
specified list
    * using a default source of randomness.  All permutations occur
with
    * approximately equal likelihood.<p>
    * <p/>
    * The hedge "approximately" is used in the foregoing description
because
    * default source of randomness is only approximately an unbiased
source of
    * independently chosen bits. If it were a perfect source of
randomly chosen
    * bits, then the algorithm would choose permutations with perfect
    * uniformity.<p>
    * <p/>
    * This implementation traverses the list backwards, from the last
element
    * up to the second, repeatedly swapping a randomly selected
element into
    * the "current position".  Elements are randomly selected from
the portion
    * of the list that runs from the first element to the current
position,
    * inclusive.<p>
    *
    * @param toShuffle the array to be shuffled.
    */
   public static void shuffle( int[] toShuffle )
       {
       // wheel is initialised only once, and only if needed.
       if ( wheel == null )
           {
           wheel = new Random();
           }
       shuffle( toShuffle, wheel );
       }

   /**
    * This method uses the same technique as Collections.shuffle, but
is
    * somewhat simpler with direct array access. Randomly permute the
specified
    * list using the specified source of randomness.  All
permutations occur
    * with equal likelihood assuming that the source of randomness is
fair.<p>
    * <p/>
    * This implementation traverses the array backwards, from the
last element
    * up to the second, repeatedly swapping a randomly selected
element into
    * the "current position".  Elements are randomly selected from
the portion
    * of the list that runs from the first element to the current
position,
    * inclusive.<p>
    *
    * @param toShuffle the array to be shuffled.
    * @param wheel     the source of randomness to use to shuffle the
list.
    */
   public static void shuffle( int[] toShuffle, Random wheel )
       {
       for ( int i = toShuffle.length; i > 1; i-- )
           {
           // swap elt i-1 and a random elt 0..i-1
           final int temp = toShuffle[ i - 1 ];
           final int otherSlot = wheel.nextInt( i );
           toShuffle[ i - 1 ] = toShuffle[ otherSlot ];
           toShuffle[ otherSlot ] = temp;
           }
       }

   // --------------------------- main() method
---------------------------

   /**
    * test driver demonstrate use of shuffle.
    *
    * @param args not used.
    */
   public static void main( String[] args )
       {
       if ( DEBUGGING )
           {
           int[] deck = new int[52];
           for ( int i = 0; i < 52; i++ )
               {
               deck[ i ] = i;
               }
           System.out.println( "\nbefore shuffle" );
           for ( int i = 0; i < 52; i++ )
               {
               System.out.print( " " );
               System.out.print( deck[ i ] );
               }

           shuffle( deck );

           System.out.println( "\nafter shuffle" );

           for ( int i = 0; i < 52; i++ )
               {
               System.out.print( " " );
               System.out.print( deck[ i ] );
               }
           }
       }
}
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

xen - 03 Oct 2007 18:20 GMT
>>        Collections.shuffle(Arrays.asList(indicies));
>
[quoted text clipped - 8 lines]
>I think it fair to say OP DID find a bug in Java, or at least the
>mother of all gotchas.

Do you even read other people's answers? Stefan Ram and I already
explained it in detail. But maybe the posts didn't reach you.
Roedy Green - 04 Oct 2007 02:24 GMT
>Do you even read other people's answers? Stefan Ram and I already
>explained it in detail. But maybe the posts didn't reach you.

Have you read my essay?  I don't think you found all of what I did.
All I saw was you are not supposed to pass an int[].

http://mindprod.com/jgloss/array.html#GOTCHAS

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 04 Oct 2007 02:27 GMT
>Do you even read other people's answers? Stefan Ram and I already
>explained it in detail. But maybe the posts didn't reach you.

Even if you had explained it in detail, there is no harm in yet
another explanation, especially one posted on a website.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 04 Oct 2007 02:45 GMT
>Do you even read other people's answers? Stefan Ram and I already
>explained it in detail. But maybe the posts didn't reach you.

You would find me less irritating if you imagined I was a sort of
translator repeating everything you said in sign language, or in
simplified language aimed an newbies.

You are imagining that whenever I say something you have already
touched on, I am correcting or publicly chastising you. Unless I
explicitly say otherwise, I am:

1. elaborating
2. simplifying
3. providing an alternative way to look at the problem.
4. asserting agreement.
5. summarising
6. attempting to turn the specific case into a general object lesson.
7. just providing repetition of an important point in slightly
different words.

The big problem most people make with me is imagining I am talking
only to them.  I almost never do that. So they get insulted when I say
something they already know or repeat something they already said.  I
am not talking to them, I am talking to the much larger audience of
newbies following along trying to learn something.

Similarly my primary goal in not to act as a help desk and get
problems solved rapidly as possible.  I want as many people as
possible (including the questioner) to learn as much as possible in
the process. Many would see what I am doing as infuriating digression.

The error you make is
1. presuming everyone reads your every word.
2. everyone understands you every word.   After all you do.

Experiments show only a tiny fraction sinks in. You need a surprising
amount of repetition of anything important.  So often missing a single
phrase can make everything that follows into Greek.  A slightly
different wording produces different ambiguities which may be enough
to get them back on track.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

xen - 04 Oct 2007 04:23 GMT
The reason I find you irritating is not because you elaborate, or
simplify, or translate, or create a webbased explanation including
code example. Those are all honorable things.

The reason is that I first state

>If you call asList() on an int[], you will get a List<int[]> with one
>element: the int[] you supplied. If you call shuffle on that list,
>nothing will change in the int[].

>If you call it with an array of a primitive type, then it cannot be
>treated as a T[] because generic types cannot be primitives. Instead,
>because int[] itself is an object, it matches the T in the signature
>and is wrapped inside an array. So what actually gets passed is not
>your int[], but an array of  int[] with one element.

And then three hours later, you state

>This code puzzled the heck out of me.

>I have done experiments and I think I now know what is going on.  It
>is far stranger than you would imagine.

suggesting to the sequential reader that you have found something new,
subsequently stating

>int[] becomes the one and only element of a List of <int[]> objects!!

While I don't mind you experimenting and coming to your own
conclusions (as I have done), it would be nice and respectful to at
least include a reference or acknowledgement to the other posters, if
you are aware of them, stating that you agree with their findings and
that you have elaborated on it to produce a code demonstration,
located on your website. You are not only targetting an audience of
newbies, you are also participating in a thread, and we are not here
to compete which each other for credits, unless you are purposefully
and irreverently trying to direct as many readers as possible to your
website. So it's not about repetition, it's about acknowledgement.

>Have you read my essay?  I don't think you found all of what I did.
>All I saw was you are not supposed to pass an int[].

Yes I read your code example and it certainly didn't explain more than
what I did, although I agree that my explanation could be improved,
for example by stating that the int[] that is wrapped inside an array
is then used as the backing for the List, thus producing a List that
is backed by an array with one int[] element, but that's not the
point.
Lew - 04 Oct 2007 14:47 GMT
Roedy Green
>> Have you read my essay?  I don't think you found all of what I did.
>> All I saw was you are not supposed to pass an int[].

> Yes I read your code example and it certainly didn't explain more than
> what I did, although I agree that my explanation could be improved,

Blah, blah, blah.

Who cares who said what, as long as good information is what's said?

Signature

Lew

xen - 05 Oct 2007 01:29 GMT
>Roedy Green
>>> Have you read my essay?  I don't think you found all of what I did.
[quoted text clipped - 6 lines]
>
>Who cares who said what, as long as good information is what's said?

Who said what is *not* the point is was making, as I clearly stated

> but that's not the point.

I just answered Roedy's question for completeness. But anyway, it
seems that Roedy was referring to himself when he said

>The error you make is
>1. presuming everyone reads your every word.

so I can't blame him for anything other than not reading others'
posts. So be it.
Roedy Green - 05 Oct 2007 04:33 GMT
>Yes I read your code example and it certainly didn't explain more than
>what I did, although I agree that my explanation could be improved,
>for example by stating that the int[] that is wrapped inside an array
>is then used as the backing for the List, thus producing a List that
>is backed by an array with one int[] element, but that's not the

Either:

1.  where you said this did not appear on my machine

2. You said it in such a way I did not understand what you meant.

3. I unconsciously skipped over reading because of I find your prose
too dense.

You making a mountain out of a molehill.  I discovered what I
discovered independently of what you said.  That happens all the time
in science.  If you are worried about credit, you get it because you
"published" first.

Even on rereading I still don't see where you explained the strange
behaviour of creating an ArrayList whose first element is an array
without error or warning.

To ensure people understand you, you pretty well have to post runnable
code.  That we all understand.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

xen - 06 Oct 2007 02:23 GMT
>Either:
>
[quoted text clipped - 4 lines]
>3. I unconsciously skipped over reading because of I find your prose
>too dense.

Aye aye, that can happen.

>You making a mountain out of a molehill.  I discovered what I
>discovered independently of what you said.  That happens all the time
>in science.  If you are worried about credit, you get it because you
>"published" first.

Well, I questioned you because I felt ignored, and after doing that I
couldn't back out now could I? :) I'm not worried about credit, I just
hate being ignored. Maybe it's like when you're with friends and you
say hey let's go to the movies and they all look at you with blank
eyes for a second and then continue discussing what they were
discussing and then five minutes later one of them says, hey let's go
to the movies and they all say yeah great idea. Something like that.

>Even on rereading I still don't see where you explained the strange
>behaviour of creating an ArrayList whose first element is an array
>without error or warning.

Okay, I'll see if I can improve things, given that you said

>Your prose is equally opaque
>to me.  I have always marveled at the ability of ordinary Germans to
>parse those giant page-long sentences.  I take it you have that skill
>too since Dutch and German come from the same roots.

I must say I have read Kant in German and I found it equally hard to
digest his sentences. Especially because I didn't understand many of
the words so I had to look them up. But when I had looked them up, I
had lost track of the rest of the sentence, so I had to start all over
again! I don't really know if Dutch people also do that, I've never
had trouble with anyone's sentence, but I guess it is very well
possible (am I doing it right now? :P).

Okay, back to my explanation.

I don't see any long sentences in it, actually. I will refrase it, and
then I want you to give your opinion, if you will.

>Arrays.asList() tries to instantiate an ArrayList on the specified
>array but an ArrayList can never be backed by an int[].

>If you call asList() on an int[], you will get a List<int[]> with one
>element: the int[] you supplied. If you call shuffle on that list,
>nothing will change in the int[].

>You don't get an error because the parameter for asList is a "T... a".
>If you call it with a T[], that array is passed.
[quoted text clipped - 3 lines]
>and is wrapped inside an array. So what actually gets passed is not
>your int[], but an array of  int[] with one element.

>There is no way for the compiler to generate an error.
>And why should ArrayList(T... t) complain? An int[] is a valid type
>parameter.

>Perhaps the compiler should generate a warning if you pass an array of
>primitive to a generic dynamic array parameter.

>Anyway, you can only solve it by using an Integer[] instead of an
>int[].

What you are trying to do with the call to asList() is to create a
List that internally uses the array that you supply, as its data
store. That way, you can modify the array by using List operations,
or, put differently, modify the List and have the changes 'write
through' to your original array.

This always works for arrays of any Object type, such as arrays of
Integer. The actual method signature for asList is »asList(T... a)«.
This means you can pass a variable amount of arguments to this
function. You could call it with asList("boy","girl","sister") or
asList("just one argument"). Internally however, all of these
parameters are wrapped inside an array, and the actual call becomes:
asList( new String[] { "boy", "girl", "sister" } ). You can also just
pass such a array directly, which is most likely how you'd use
asList(). There is only one caveat: the type of the parameter, and as
such, the type of the elements of the array, must conform to the
generic type variable »T«. But only object types can match a generic
type. You cannot match a »T« with any primitive type, such as »int«.

So what happens when you call asList() on an int array? First the
compiler tries to match T with int, but that doesn't work. However,
there is another option open to the compiler: it can match T with
int[]. That's right, array of int becomes the type T. As such, this
int[] is the single parameter to asList(), and it gets wrapped inside
an array, like all single parameters that are not already an array of
an object-type. This single element array with type signature int[][]
is then used as the backing for a new ArrayList. That means that the
List that you get, has a single element: the int[] you originally
supplied!

It should be clear that calling shuffle() on this List will only
effect the encapsulating array and will do nothing to the int[] that
is kept inside.
Stefan Ram - 06 Oct 2007 02:55 GMT
>hate being ignored

 But then, in Usenet, there is a history and tradition of using
 a »filter« or »scoring system«.

 No one is obliged to read all articles posted to a group.

 Moreover, Usenet is not real-time communication. Someone
 might answer to an article and not have yet read another
 answer to the same article that might not have arrived at his
 newsserver yet.

 There is also a tradition to read and answer Usenet articles
 off-line, after a client has fetched some articles from a
 Usenet server. In this case, some more recent articles also
 might not be read yet when answering to an article.

>>parse those giant page-long sentences.  I take it you have that skill
>>too since Dutch and German come from the same roots.
>I must say I have read Kant in German and I found it equally hard to

 Hausser wrote a computer program that can parse German
 sentences, which most native German speakers will have
 a hard time to understand:

     »Der Mann hat dem Mädchen das Buch geben
     dürfen können wollen sollen mögen.«

 This should mean: »The man wanted to be required to want
 to be able to be allowed to give the book to the girl.«

 [Hausser86]
   Lecture Notes in Computer Science Vol.231
   NEWCAT, Parsing Natural Language Using Left-Associative Grammar
   Roland Hausser
   ISBN: 3-540-16781-1; Springer; 1986; Berlin, New York
xen - 06 Oct 2007 06:23 GMT
>  No one is obliged to read all articles posted to a group.

No, of course. But for a thread you participate in it is slightly
different. My friends are not obliged to listen to me when I speak,
but it would be nice of them nonetheless.

>  Moreover, Usenet is not real-time communication. Someone
>  might answer to an article and not have yet read another
[quoted text clipped - 5 lines]
>  Usenet server. In this case, some more recent articles also
>  might not be read yet when answering to an article.

Aye, that's all possible but not very likely nowadays. When I post a
message it's almost instantly available on Google. But, granted, I can
never be sure someone has (had the opportunity to) read me.
Lasse Reichstein Nielsen - 06 Oct 2007 11:49 GMT
> Aye, that's all possible but not very likely nowadays. When I post a
> message it's almost instantly available on Google. But, granted, I can
> never be sure someone has (had the opportunity to) read me.

What's Google got to do with it? I read news in a newsreader, retrieving
the messages from my ISP's nntp-server. My posts are also sent to that
server. That means that other people reading news using the same server
will see my messages sooner than other people. I will also see messages
from servers that propagate directly to my ISP's server sooner than
messages posted to servers requireing more hops to reach me.

You can, usually, assume that someone seeing a response has also had
the chance to seeing the message being responded to, but I bet there
can be cases where even that isn't true. Other responses to the same
message cannot be assumed to have arrived when a response is written.

/L 'but at least Usenet distribution is no longer magnetic tape on a plane'
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

xen - 06 Oct 2007 18:54 GMT
>> Aye, that's all possible but not very likely nowadays. When I post a
>> message it's almost instantly available on Google. But, granted, I can
>> never be sure someone has (had the opportunity to) read me.
>
>What's Google got to do with it?

I just mentioned Google because it is a source of news other than my
own ISP's newsserver, so if it has propagated to Google Groups, there
is I think a reasonable chance that it is has progapaged or will
propagate in a reasonable amount of time to Your Favourite Newsserver
as well.
xen - 04 Oct 2007 05:02 GMT
Btw,

I would suggest to change

>* You don't have the usual asList backing int[] array or a backing Integer[] array.

into something more understandable. What does »asList backing int[]
array« mean? asList is not backing anything, nor is it backed by
anything. And even if it was, I don't understand it.
Lew - 04 Oct 2007 14:49 GMT
> Btw,
>
[quoted text clipped - 5 lines]
> array« mean? asList is not backing anything, nor is it backed by
> anything. And even if it was, I don't understand it.

Yes, it is.

asList() returns a List backed by the array, thus "the backing array".

The Javadocs for asList() clearly state:
> Returns a fixed-size list backed by the specified array.

So the "backing" (gerundive) array is that "specified" array.

Simple.

Signature

Lew

xen - 05 Oct 2007 01:40 GMT
>> I would suggest to change
>>
[quoted text clipped - 14 lines]
>
>Simple.

The List is backed by the array, not asList. asList is not backed by
anything, other than maybe ArrayList(T... t).
And backing is ambiguous. You could also read it as "the usual Josh
throwing Jim in the pond" and then it's still ambiguous.

But anyway, suit yourself.
Lew - 05 Oct 2007 04:46 GMT
> The List is backed by the array, not asList. asList is not backed by
> anything, other than maybe ArrayList(T... t).
> And backing is ambiguous. You could also read it as "the usual Josh
> throwing Jim in the pond" and then it's still ambiguous.

I have read and re-read your post, and I still don't know what you're trying
to say.

I agree that saying "asList" has a "backing array" is not precise,
nevertheless, it's what was meant.  You asked what it meant and professed not
to understand; now I see that that was under false pretenses, and that in fact
you disagreed with the idea, and that you understood it just fine.

The poster who used the term "backing array" was using a standard term (the
usage of "backing" in this sense being well established) in a colloquial way,
using the method name as a metonymic reference to the list returned by the
method.

Nothing ambiguous at all, just imprecise.  Saying "ambiguous" for something
that has only one interpretation is imprecise.

Signature

Lew

xen - 06 Oct 2007 01:23 GMT
>I agree that saying "asList" has a "backing array" is not precise,
>nevertheless, it's what was meant.  You asked what it meant and professed not
[quoted text clipped - 8 lines]
>Nothing ambiguous at all, just imprecise.  Saying "ambiguous" for something
>that has only one interpretation is imprecise.

Look. Of course I knew in a way what he was trying to say, because I
already knew what was going on regarding this phenomenon, so I didn't
need him to explain it to me.

But, and maybe this is because I'm not a native English speaker, when
I read that sentence, the machinery of my grammar recognition faculty
just grinded to a halt. I couldn't process that part of the sentence.
I just couldn't make anything out of it. I had to 'manually' take
"asList backing int[] array" out of context, interpret in terms of the
gerundive as you call it, and then reinsert it in the sentence. If I
just read the sentence as it is, I automatically interpret "backing"
as a verb of which "asList" is the subject, and then it doesn't make
sense. So, to me, it is one hell of a difficult sentence to interpret
correctly. If you'd insert one small "an" it would become "the usual
asList backing an array" and the whole meaning changes.

So, whether it is correct English or not, it is clearly not suitable
for all readers, and it's not as if I'm so bad at English.
Roedy Green - 05 Oct 2007 04:40 GMT
>I would suggest to change
>
[quoted text clipped - 3 lines]
>array« mean? asList is not backing anything, nor is it backed by
>anything. And even if it was, I don't understand it.

I will see if I can improve the wording. Your prose is equally opaque
to me.  I have always marveled at the ability of ordinary Germans to
parse those giant page-long sentences.  I take it you have that skill
too since Dutch and German come from the same roots.

When I was in high school my English teachers chastised me for my
overly simple syntax.  One liked it, saying it reminded him of Latin.
It just that any sort of nesting causes my brain to explode.  I have a
terrible time with parenthesis nests in Java or nested ifs.

I have greater motivation that most to encapsulate, so that I don't
have to keep too many details in mind at once.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 05 Oct 2007 04:50 GMT
>>* You don't have the usual asList backing int[] array or a backing Integer[] array.
>
>into something more understandable

the comment at the head of the gotchas snippet now reads:

Demonstrate Arrays.asList( int[] ) gotcha.

See the goofy thing happening with Arrays.asList( int[] ).

int[] becomes the one and only element of a List of <int[]> objects!!
Arrays.asList is advertised to support the original array as a backing
array so that when you change the List (actually an ArrayList)
produced by asList, the original array is also supposed to change.
However, if you attempt to do Arrays.asList( int[] ), this won't work.
There is no invisible backing int[] or Integer[] created either.
All I can say is don't feed an int[] to asList. Use
Arrays.asList(Integer[]) boxed manually.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

xen - 06 Oct 2007 01:36 GMT
>>>* You don't have the usual asList backing int[] array or a backing Integer[] array.
>>
[quoted text clipped - 14 lines]
>All I can say is don't feed an int[] to asList. Use
>Arrays.asList(Integer[]) boxed manually.

Well Roedy, maybe it's just a matter of personal opinion or
preference, but.... I think what you wrote is just incorrect.

>There is no invisible backing int[] or Integer[] created either.

Actually, there IS a backing array. It's just that it is an int[][]
with one element: the int[] the caller supplied. This means that all
the List operations will index this array by way of the first of the
indeces, like elements[2], whereas to get an element of the original
int[] you'd use elements[0][x] where x is an index of the original
int[]. But I don't think I need to explain this to you (but just to
make sure ;)).

So while my prose may be hard to digest (and I'm wanting to look into
that, thank you for telling me) I find your explanation to be just not
very insightful or insight-giving.

Thanks for discussing this with me anyway, I appreciate it.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.