Hai Chuan Wang <wangh...@cn.ibm.com> wrote on 04/05/2011 05:11:39 AM:
>
> I'm writing a data structure with generics, and needs an internal array
to
> store data.
> But the array should be initialized with null value at the beginning.
>
> public class Seq[ET] {
>     public var S:Array[ET](1){rail};
>     public var sz:int;
>
>     public def this(s:int) {
>       sz = s;
>             S = new Array[ET](sz, null); //<==== problem here
>     }
> }
>
> Because ET has no "hasZero" attribute. I don't know how to create the
array
> with null as initial value.
>
> new Array[ET](sz, null), will treat "null" as "(int)=>ET", and throw NPE.
> null cannot be casted to ET type, either.
>
> Anyone can give some suggestions?

Array is intended to be type safe, and in X10 an unconstrained T could be
instantiated on some type S such that sizeof(S) bytes of zero's is not a
valid value of type S.  So, Array has been written to prevent you from
doing this.

What you can do is:
        (a) add the {ET haszero} constraint to Seq which will prevent such
instantiations and thus allow you to call the Array constructor that
zero-initializes the backing storage.
        (b) force the user to provide an "initial value" in the constructor
and use that to initialize the array.
        (c) instead of using Array, use ArrayList or IndexedMemoryChunk for
your backing storage. Both of these sidestep this piece of the X10 type
system.  ArrayList does it by using an IMC under the covers, while not
allowing clients to see any uninitialized values.  So ArrayList is type
safe, but has some constraints on how it can be used (in particular, you
always have to densely use the indices elements from 0...size-1; you can't
have gaps).  IndexedMemoryChunk is not typesafe.
        (d) You can make your backing array be an Array[Cell[T]].  This
injects an extra-level of indirection, and will not perform as well as the
other solutions.

Personally, I think (a) is the most viable solution.  I think it is a
fairly natural outcome of the design point taken by the X10 type system
that many generic collection types should have the {T haszero} constraint
on them to allow efficient implementation.  Arguably, this change should be
made in the x10.util collection classes as well. This then forces clients
that need to put types that don't satisfy the haszero constraint into
Cells/Boxes themselves before inserting them into the collection.  This is
cumbersome, but I would suggest is putting the programming burden where it
most likely belongs.

--dave
------------------------------------------------------------------------------
Xperia(TM) PLAY
It's a major breakthrough. An authentic gaming
smartphone on the nation's most reliable network.
And it wants your games.
http://p.sf.net/sfu/verizon-sfdev
_______________________________________________
X10-users mailing list
X10-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/x10-users

Reply via email to