Java collections in D

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Oct 11 13:18:01 PDT 2006


"BLS" <nanali at wanadoo.fr> wrote in message 
news:egj4g4$1gpa$1 at digitaldaemon.com...
> Hi,
> I like to translate the following Java code into D. (reason follows)
>
> **
>  * Collection interface; the root of all Java 1.5 collections.
>  */
> public interface Collection<AnyType> extends Iterable<AnyType>, 
> java.io.Serializable
> {
>     int size( );
>
>     boolean isEmpty( );
>
>     // and so on ..............
>     /**
>      * Obtains an Iterator object used to traverse the collection.
>      * @return an iterator positioned prior to the first element.
>      */
>     Iterator<AnyType> iterator( );
>
>     /**
>      * Obtains a primitive array view of the collection.
>      * @return the primitive array view.
>      */
>     Object [ ] toArray( );
>
>     /**
>      * Obtains a primitive array view of the collection.
>      * @return the primitive array view.
>      */
>     <OtherType> OtherType [ ] toArray( OtherType [ ] arr );
> }
>
> Reason :
> Converting (a lot of ) Java code into D requires java collections in D. 
> (also automatic Java2D translation will benefit)
>
> Questions :
> 1) exists allready something simular to ITERABLE, SERIALIZABLE (have not 
> seen the interf. yet)

Serializable doesn't really have much of an analogue in D.. Java seems to 
treat it as special (even going so far as to have a keyword to prevent 
serialization of a member variable, "transient"), but there is no standard 
serializing mechanism in D.  It's useful if you want to have all your 
collection types able to be serialized to some kind of file (disk, over 
network etc.), but if you don't need that kind of ability..

As for Iterable?  The way Java does "foreach" (for(member : collection)) is 
also different than how D does it.  D accomplishes foreach iteration through 
an opApply method.  I suppose it would be possible to make an Iterable 
templated interface which means that the derived class must implement 
opApply, like:

interface Iterable(Type)
{
    int opApply(int delegate(inout Type index) dg);
}

class Foo(T) : Iterable!(T)
{
    int opApply(int delegate(inout T index) dg)
    {
        // whatever
    }
}

> 2) <OtherType> OtherType [ ] toArray( OtherType [ ] arr );
> Simply ??????.

In D, this would just be

OtherType[] toArray(OtherType[] arr);

According to the Java specs, it will attempt to put the collection's 
contents into the passed-in array, but if it doesn't fit, it'll make a new 
one and return that instead. 





More information about the Digitalmars-d-learn mailing list