Array of generics (JLS seems too restrictive)

Hi everybody,
with some friends (in a lab) we currently develop a compiler generator
(a la SableCC i.e SLR, LR, LALR).
Because we start last june, we develop using jdk 1.5 and
generics. For me, i think it save us lot of time mainly because
Map<NonTerminal,Map<LRItem,Node>> is more readable
than Map :)
And this is my question : why CREATION of array of generics is unsafe ?
I don't understand why a code like below is tagged unsafe :
HashMap<State,Action>[] maps=new HashMap<State,Action>[5];
for(int i=0;i<map.length;i++)
  maps=new HashMap<State,Action>();
For me, the fact that JLS forbids array of generics creation
is too restrictive, only cases where type parameter are lost
should be tagged as unsafe.
Example :
Object[] array=maps; // unsafe
Object o=map;            // weird but unsafe because
                                      // Object[] o=(Object[])(Object)maps; must be unsafeWhat do you think about this ?
R�mi Forax

The question is why :
Future<Double>[] futures=new
Future<Double>[10000];
is not allowed. It seems safe !First of all, it would not be safe. The example below would exhibit exactly the same vulnerabilities with this assignment as it would with any of the allowed ones. This is because both the declared type and the runtime type would still be the same.
It seems the current implementation is not able to detect (and warn about) the unsafety of the assignment above. That's why you're not allowed to use it: allowing it would provide a very false sense of type-safety
and why :
Object[] o=futures;
is not tagged unsafe.
It's unsafe because you can write :
Object[] o=futures;
o[0]=new Future<String>(); // for the example, let
says Future is a class
R�mi ForaxThis is probably done to avoid redundancy. As far as I can see, in all cases where this could be unsafe, you have been notified about the lack of safety already when you first assigned to futures.

Similar Messages

  • How to create an array of generics?

    I have the following snippet of code using array of vectors:
    Vector[] tmpArr = new Vector[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector();
    String str = ...
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    And I want to convert to generics:
    Vector<String>[] tmpArr = new Vector<String>[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector<String>();
    String str = ....
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    But the first row gives me an error:
    -->Generic array creation.
    If I change it in
    Vector<String>[] tmpArr = new Vector<String>[n];
    (as I've seen in a pdf by G.Bracha talking aout collections)
    it gives me the error:
    -->cannot find symbol
    -->method add(String)
    in the
    tmpArr[j].add(str);
    row.
    The only way it seems to work is
    Vector<String>[] tmpArr = new Vector[n];
    but it gives me the unchecked conversion warning.
    How can I create an array of generics?
    Thank you!
    Matteo

    You can't
    Actually, that depends on the exact definition of a generic array. If by generic array someone means "an array comprised of elements defined by a type parameter", there is a solution.
    import java.lang.reflect.Array;
    public class Something<T> {
        private final Class<T> type;
        public Something(Class<T> type) {
            this.type = type;
        public String getTypeName() {
            return this.type.getName();
        public T[] newArray(final int length) {
            return (T[]) Array.newInstance(this.type, length);
    }The constructor introduces the type information (T) to the runtime environment, which means an instance of Something will know its type. Method newArray therefore does not cause a warning on unchecked type conversion, so this approach is typesafe.
    // Type parameter class is demanded by constructor...
    Something<String> stringThing = new Something<String>(String.class);
    // Cheating won't work, because the compiler catches the error...
    Something<Vector> vectorThing = new Something<Vector>(Integer.class);This approach, however, doesn't enable you to create an array of typed elements (like Vector<String>[]). If that is the definition of a generic array, then it is indeed not possible to create one.
    After all, while Vector[].class exists and can be resolved at runtime, there's no such thing as Vector<String>[].class, so there's no way you could provide the class definition of the component type to the constructor of Something.
    This may be a surprise to mdt_java, because if I remember correctly, templates in C++ cause actually different classes to be created for 'generic' types. This is not the case with Java.

  • HT201250 Hi, I hope this question won't seem too basic but if I want to use a new larger external drive for my time machine backups, will it do a new full backup the first time I plug it in and if so, do I really need all the old backups on my smaller ext

    Hi, I hope this question won't seem too basic but if I want to use a new larger external drive for my time machine backups, will it do a new full backup the first time I plug it in and if so, do I really need all the old backups on my smaller external drive?

    50maz wrote:
    Hi, I hope this question won't seem too basic but if I want to use a new larger external drive for my time machine backups, will it do a new full backup the first time I plug it in
    Yes, it will do a full backup.
    and if so, do I really need all the old backups on my smaller external drive?
    Only if you want to be able to go back in time to those previous Time Machine backups.  When you plug in the new larger external drive, you will only be able to go back as far as the first day you plugged it in and ran the first Time Machine backup on it.

  • Array of generic class

    Hi.
    i have to create an array of generic class
    ex: GenericClass<E> [ ] x = new GenericClass<E>[ y ]
    is it possible?
    i can create GenericClass<E> [ ] x; but i can't initiate it in this way..
    Someone know how i can do it?

    crosspost
    http://forum.java.sun.com/thread.jspa?threadID=746524&messageID=4272614#4272614

  • TS3899 How to cancel a sent file that seems too big to be sent - but keeps trying thus draining the battery?

    How do I cancel a file that is trying to be sent but seems too big to be sent - it keeps trying to send andconstantly drains the battery.
    Sandy

    Try force-closing Mail: double-tap the home button, locate Mail in the list at the bottom, tap and hold it until it wiggles, tap to close it, finish by tapping the home button.  Then go the you email provider's webmail site (such as iCloud.com for @me.com mail), log into your account and delete any emails you find in your Drafts folder.  Then open Mail again and see if it stopped trying to send.

  • Is the points system too restrictive?

    When I first joined these forums, the points system was quite different, so that the transition from level three to four took a long time, but was possible. Since then giving and receiving points has tightened up so much that I now think that it is all but impossible to get from level two to level three in a reasonable time.
    I would like to know how many people have made the level three to four transition since the current point regime started? and of those, how many were already close to the transition at the changeover?
    Is the current scheme too restrictive? Was it cynically designed to be restrictive to reduce the number of people getting to level four?
    Bob

    Majordadusma leveled on 6/20/06.
    Okay. There may still be some overlap between this list and yours.
    *Carried up to L4 by the points conversion at the time of the transistion*
    b noir (from L2)
    Buegie (from L3)
    StarDeb55 (from L3)
    *L4 level achieved some time after the transition*
    Alan Somers
    AxL
    Bryan Mick
    David S.
    Dick Napoli
    F Shippey
    Francine Schwieder
    Michael Lafferty
    Otto42
    QuickTimeKirk
    The hatter
    Anyone there you've already got, Ronda?

  • HELP! Can I retrieve my previous session? I only just ticked the "open with previous session" preference but it seems too late! Can I still get the old pages/tabs I had open?

    HELP! Can I retrieve my previous session? I only just ticked the "open with previous session" preference but it seems too late! Can I still get the old pages/tabs I had open?

    That could be a problem, unfortunately.
    But most likely the pages you were on are stored in the History list. Try pressing Cmd+Shift+H to get the History window.
    To help prevent this from happening to you again in the future, I can recommend the extension [https://addons.mozilla.org/en-US/firefox/addon/2324/ Session Manager]. It is quite powerful but may not be able to help you any more than the History at this point.
    Please let us know how above works out, and if we can be of further assistance. Detailed feedback is appreciated and helps us to help more users with similar problems.

  • HELP! Can I retrieve my previous session? I only just ticked the "open with previous session" preference but it seems too late!

    HELP! Can I retrieve my previous session? I only just ticked the "open with previous session" preference but it seems too late! Can I still get the old pages/tabs I had open?

    That could be a problem, unfortunately.
    But most likely the pages you were on are stored in the History list. Try pressing Cmd+Shift+H to get the History window.
    To help prevent this from happening to you again in the future, I can recommend the extension [https://addons.mozilla.org/en-US/firefox/addon/2324/ Session Manager]. It is quite powerful but may not be able to help you any more than the History at this point.
    Please let us know how above works out, and if we can be of further assistance. Detailed feedback is appreciated and helps us to help more users with similar problems.

  • I revive messages from everyone but one person on my phone I had my iMessage on my iPad but I turned it off and also off on my phone but I can't seem too receive messages from them but they get mine,?

    I revive messages from everyone but one person on my phone I had my iMessage on my iPad but I turned it off and also off on my phone but I can't seem too receive messages from them but they get mine,?

    They have an iOS device? If so, have them send as an SMS, not an iMessage.

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • Socket seems too slow...maybe java.nio?

    Hello
    In our system I have to receive Multicast Packets repeats very quick(1-5 ms). I have to link them one after an other in the order they sent. And if I miss a packet, something will go wrong...
    I have to listen to different IPs and I use different threads for different IPs. If I use only one thread (and listens to only one IP) everything seems ok.
    But if I starts listening to an other ip too, I miss 2 packets in a row, or only one if I turn off parsing the message (XML).
    Here is the code I use in the Threads:
    try{
                   socket = new MulticastSocket(port);
                   socket.setSoTimeout(1000);
                   inetAddress = InetAddress.getByName(ip);
                   NetworkInterface nInterface=
    NetworkInterface.getByName(networkInterface);
                   if(nInterface!=null)socket.setNetworkInterface(nInterface);
                   socket.joinGroup(inetAddress);
              catch(IOException ioe){
                   logger.error(ioe.getMessage(), ioe);
    return;
              try{
                   while (!interrupted()) {
                        try{
                             byte[] buffer = new byte[1480];
                             packet = new DatagramPacket(buffer, buffer.length);
                             socket.receive(packet);
    parse(buffer);
                        }catch(SocketTimeoutException stoe){
                             //     DO NOTHING
                        }catch(IOException ioe){
                             logger.error(ioe.getMessage(), ioe);
              }finally{
                   try {
                        if(socket!=null){
                             socket.leaveGroup(inetAddress);
                   } catch (IOException ioe) {}
    Every Thread has its own parsing object.
    Any tips, what is wrong?
    Maybe java.nio could solve the problem somehow. There is a sample server in [Java Home]/sample/nio/server and it suggest that there are quicker methods to receive messages from different IPs (maybe Blocking/Pooled-Thread Server). But I can't understand the API and the Sample while I was reading it (20-30 minutes).
    Could it be quicker? Does it worth toying with the idea?
    Thanks:
    Bence

    In our system I have to receive Multicast Packets
    repeats very quick(1-5 ms). I have to link them one
    after an other in the order they sent. And if I miss
    a packet, something will go wrong...There is no guarantee anywhere in the system that you won't miss a datagram. UDP doesn't make such guarantees. If you need all the packets you will have to build ACK or NACK into your protocol.
    You can alleviate the problem by running a very large socket receive buffer. But you can't eliminate it. Rethink this.
    NIO is not significantly quicker for applications like this, it is more scalable.

  • TP3 - Generic JDBC Seems Not Working - Connection Worked in TP2 but Not TP3

    I had a connection working in TP2 to a PosgreSQL database. I have done in TP3 exactly what I did in TP2 to set up the connection but the connection test fails listing the name of the driver.
    I put the JAR in jdev\lib, I added a class/library to the default project properties with the classpath listing the location of the JAR including the filename, then I created a new connection with the same driver name, user/password, and JDBC URL I used in TP2. None of this worked though. I even tried restarting JDeveloper.
    Any ideas on what I could be doing wrong or if something new needs to be done in TP3?
    On a side note, although I got the connection working to the PostgreSQL db working in TP2, JDeveloper was never able to find its tables like when creating an entity from a table for example. I know this is not an issue with the driver JAR because this works flawlessly in Netbeans 6.
    Thanks in advance for any help.
    KurzHome

    Hi CM and Chris,
    I have the exact same problem when I tried to create a connection to SQL Server 2005 using Generic JDBC. It worked well for TP2 but does not work for TP3. Further more if you create it anyway, you will get following message in testing:
    An error was encountered performing the requested operation:
    com.microsoft.sqlserver.jdbc.SQLServerDriver
    Vendor code 0.
    I tried to export the working connection from JDeveloper 10.1.2. and import it to TP3. I could not solved the problem.
    Then I export the SQL server connection from TP3. The connection is expressed as
    <Reference credentialStoreKey="yuwyuw" className="oracle.jdeveloper.db.adapter.DatabaseProvider" name="yuwyuw">
    <Factory className="oracle.jdeveloper.db.adapter.DatabaseProviderFactory"/>
    <RefAddresses>
    <StringRefAddr addrType="subtype">
    <Contents>thirdParty</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="user">
    <Contents>yuw</Contents>
    </StringRefAddr>
    <SecureRefAddr addrType="password"/>
    <StringRefAddr addrType="driver">
    <Contents>com.microsoft.sqlserver.jdbc.SQLServerDriver</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="DeployPassword">
    <Contents>false</Contents>
    </StringRefAddr>
    <StringRefAddr addrType="customUrl">
    <Contents>jdbc:sqlserver://host:1433</Contents>
    </StringRefAddr>
    </RefAddresses>
    </Reference>
    It seems DatabaseProviderFactory could not create connection other than Oracle. BBut JDev10.1.2 does not use Factory class. I tested Driver and URL by a small program that created a connection using connection string. No problem at all.
    Now I have 2 questions:
    1)How can we access the source code to see what happens when we submit connection creation request?
    2)You mentioned that we can swap JVM version. But this can only be done on project level. Can we do it on IDE level, because IDE connection is not associated with any project.
    Thanks,
    wyuwyu

  • Creating array of generic object

    hello, what i want to do is something like:
    public class AClass<K extends SomeObject>{
        SomeObject[] AnArray;
        public void amethod() {
            AnArray=new K[10];
    }So I want to create an array of some kind of object at runtime without already know the kind of the object. The thing is that I think that generics are only "known" at compiling time, so this AnArray=new K[10]; is propably completely wrong but I cannot think of any other way of creating an array without knowing in advance the kind of object....So if someone could enlighten me on how to do this...
    if this is of any help the reason i want to have such implementation is that this array is supposed to be a hashmap and the SomeObject is supposed to be a super class of some different kind of LinkedList classes, so I want the hashmap to be flexible on what kind of list will be used. Suggestions for completely different approach are also welcome offcourse, but I would prefer it if someone could give some brief explaination on how manipulating such a generic array issue...

    Hi Fraksia,
    Unfortunately, array creation of type parameters is not allowed, so you can't
    say new T[3]; That is because T doesn't exist at compile time. It is erased.
    It is misleading - I know. Because when you say
    AClass<SomeObject> aclass=new AClass<SomeObject>();you might thing that T becomes SomeObject in your class wheres
    what that does is that whenever you expect your type parameter in
    the calling code, compiler will insert a cast. See the example below:
    class MyClass<T> {
       T o;
       public MyClass(T o) {
          this.o=o;
       public T get() {
          return o;
    class CallingClass {
       public static void main(String[] args) {
          MyClass<String> m=new MyClass<String>("Test");
          String o=m.get();  //no cast needed here
    }Benefit: increased type safety, no casts needed in the CallingClass.
    What really happens is:
    class MyClass {
       Object o;
       public MyClass(Object o) {
          this.o=o;
       public Object get() {
          return o;
    class CallingClass {
       public static void main(String[] args) {
          MyClass m=new MyClass("Test);
          String s=(String)m.get();  // compiler inserts cast here based on your type parameter
    }That is why you can't do what you wanted - because "there is no spoon" ;)
    Generics in Java are only a compile time feature.
    Cheers,
    Adrian

  • Can't seem to restrict access to screen sharing

    I'm running a macbook pro (10.6.2). I'm at my folks' place for the holidays and I tried screen sharing into my MBP from my dad's iMac (10.6.2) and noticed that I could access the MBP screen without any password prompt.
    I went into my MBP sharing system preferences and set screen sharing to: "Allow access for only these users: <my login>"
    Again, I tried accessing my MBP screen from the iMac, and again I was able to get in without any password prompt.
    Now I'm using my dad's login on his iMac, which is completely different from my MBP login which I thought I had limited screen sharing to. All of this is taking place within a home network.
    I would like to allow screen sharing on my MBP, but only if it's password protected. Can anyone see what I'm doing wrong here? Why does my MBP keep allowing open access to screen sharing when it appears that I am restricting it to only my profile?
    I tried messing with the options in "computer settings", but that didn't seem to help either.

    I would suspect that the first time you did it (may have been a while back) the password was saved in your father's keychain on the imac.
    open keychain access on the imac and see if it's there. if you delete the keychain entry for that password it should ask again next time you try to connect. and don't check the box to remember the password in the keychain.

  • Initializing an array of generics

    Hello all,
    I have declared an array of Vector with generics. The declaration is OK but the initialization gives me an error.
    This is the declaration
    Vector<Integer>[] x;This must be an array. Each element of the array is of type Vector<Integer>.
    I tried to initialize it using the line
    x = new Vector<Integer>[4];but it didn't work.
    I also tried
    x = new Vector[4]<Integer>;but didn't work also. The only initialization that worked is
    x = new Vector[4];But I want to put the generic tag in the initialization because it gives me warning.
    Any suggestions?
    Regards,
    Ahmed Saad

    x = new <Integer> Vector[4];When I compile that with Sun's javac compiler, I
    still get a warning.
    If you are not, it's a bug in the compiler you are
    using.
    As far as I know, the code above is no different
    from:
    x = new  Vector[4];
    yeah, I am trying to solve the same problem, and despite the person posting it worked, it didn't get rid of the problem for me...
    private Vector<Object> [] data;
    X.java:nn: generic array creation
    this.data = new Vector<Object>[2];
    X.java:nn: warning: [unchecked] unchecked conversion
    found : java.util.Vector[]
    required: java.util.Vector<java.lang.Object>[]
    this.data = new Vector[2];
    X.java:nn: warning: [unchecked] unchecked conversion
    found : java.util.Vector[]
    required: java.util.Vector<java.lang.Object>[]
    this.data = new <Object>Vector[2];
    ^

Maybe you are looking for

  • SSO for 'external' partner apps

    Is it possible to use oracle's SSO product with applications written in various languages (php/perl/coldfusion/.net,etc) on non-oracle servers. ie, if i have a php application that sits on a server entirely separate from the oracle app server or SSO

  • Abends - CLIB and GWIA - me too

    Running GW 8.0.2 on NW 6.5.6 (was recommended not to patch NW due to Backup Exec) Starting at 5:02 pm on January 19th we began to get Abends on our GW server. I have since determined that we only get them when one specific user's Sprint HTC EVO estab

  • Non modvatable duty not calculated in invoice tab of PO

    Hi expert, We have recently updated application support pack (SAPKH47030) on our enterprise version and facing following problem - One tax code for 2% CST bearing JM02 condition type (TAXINJ) and assigned with accounting key NVV having 100% mention w

  • Why is vendor negative when posting invoice in MIRO

    Hi all, I have a very basic question. When posting an invoice in MIRO, why is the vendor GL account negative? I assume this is vendor A/P, so shouldn't it increase in an invoice? ie.. vendor   5.00- GR/IR  5.00 + If you have a website to redirect me

  • Website in several language

    Hi! I have publish my website in swedish with my iweb and it is ok but now I would like to have the same website in another language. I would have in my first webpage (the welcome page) a link to my website in english. Is it possible with iWeb? I wan