LayoutWindow.getSelectedObjects()?

Help
Pete
2016-03-28
2016-03-30
  • Pete

    Pete - 2016-03-28

    Hi!

    The API documentation says that the getSelectedObjects()of LayoutWindow should produce a collection of ObjectInfos.

    Still selection = window.getSelectedObjects().toArray(); in the code causes an error in the compiler, when the type of selection is ObjectInfo[]:

    [javac] required: ObjectInfo[]
    [javac] found: Object[]

    What is that about? If I define selection as Object[] then it works, but that is not very useful in this case.

    I have a workaround that looks something like this:

        int[] indices = window.getSelectedIndices();
        ObjectInfo[] selection = new ObjectInfo[indices.length];
        for (int o = 0; o < indices.length; o++)
            selection[o] = window.getScene().getObject(indices[o]);
    

    -P-

     
    Last edit: Pete 2016-03-28
  • Alain Bonnaud

    Alain Bonnaud - 2016-03-29

    Hi,

    window.getSelectedObjects() return Collection<ObjectInfo>, but toArray() return (java.lang.)Object[].
    The found Object[] is not the AOI one but the java.lang Object.

    Your workaround is very similar to the code of getSelectedObjects().

     
  • Luke S

    Luke S - 2016-03-29

    To go a little deeper, this is a side effect of the way the Generics System works.

    In AOI source, getSelectedObjects() returns a Collection <ObjectInfo> The compiler checks to make sure that you don't do anything silly like try to cast one of the items it contains to com.aquarium.fish.Guppy but at runtime, it's just a Collection <Object> and has no idea what is actually contained. This is called 'type erasure.'

    There is a better way to get an array, though. If you pass in a pre-initialized array of the correct type, Collections will return a type specific array. It would look something like this:

    Collection selection = window.getSelectedObjects();
    ObjectInfo[] selected = selection.toArray(new ObjectInfo[selection.size()]);
    

    See the Collections API and Collection javadoc for details.

    What I'm wondering is why you need an array? you can itterate through any Collection with standard methods, and get a refernce to any member item, to modify as you wish.

     
  • Pete

    Pete - 2016-03-30

    Well, basically that was just a lazy man's shortcut: I am not that familiar with lists and collections and in scripting the toArray() worked just fine. In this case the scripting engines automatically find the ObjectInfo behind the java-Object.

    Though obviously a collection is sometimes a nicer way of handling data than a rigid array. It just looks quite a bit different.... so "Go study!" to me. :)

    Thanks

     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks