Describe non-generic array cast in JLS3 as being unchecked

This method :
    static <T, U extends T> U[] cast(T[] a) { return (U[]) a; }will generate the warning: [unchecked] unchecked cast, found: T[], required: U[].
And it should. Wouldn't it be appropriate if
    static Object[] cast(String[] a) { return (String[]) a; }would produce the same warning?
If you do that, you could translate the declaration
  T[] at = new T[255]
  String[] as = new String[255]into
Array<T> at = Array.<T>newInstance(255);
Array<String> as = Array.<String>newInstance(String.class, 255);where java.lang.reflect.Array would be something like
package java.lang.reflect.Array;
public final class Array<T> implements Iterable<T> {
    public final int length;
    private Type memberType;
    private Array(Type memberType, int length) {
        this.memberType = memberType;
        this.length = length;
    public native T getMember(int i);
    public native void setMember(int i, T member);
    public native java.util.Iterator<T> iterator();
   public static <U> Array<U> newInstance(int length) {
       return new Array<U>(null, length);
   public static <U> Array<U> newInstance(Class<U> memberClass, int length) {
       return new Array<U>(memberClass, length);

Sorry, I created a bad example. It should have been:
    static <T, U extends T> T[] cast(U[] a) { return (T[]) a; }and
    static Object[] cast(String[] a) { return (Object[]) a; }The point is that an array of String is different from an array of Object and casts between them is unsafe. Throwing an ArrayStoreException if the wrong type is assigned is just a workaround for lack generic types in pre-Tiger Java. Now that we will have generics, I think it would be appropriate if Java arrays would be treated as proper generic types. For those that are afraid of breaking backwards compatiblility, the erasure mechanism should be able to take care of that.

Similar Messages

  • Generic arrays

    I want to make an array of LinkedLists of Doubles. I tried:
    LinkedList<Double> buckets = new LinkedList<Double>[n];which gave me an error because I'm creating a generic array. On the other hand, if I do
    LinkedList<Double> buckets = new LinkedList[n];I get a warning suggesting that the compiler was looking for the first version!
    How do I do this?

    McNepp wrote:
    It seems to be a common misconception that one has to
    resort to Reflection in order to create arrays
    of generic types.It is not a misconception. On the contrary. It depends on what the library writer is trying to achieve. If I understand Neal Gafter in his blog http://www.gafter.com/~neal dated from September 23rd titled Puzzling Through Erasure: answer section correctly - currently his site is unavailable but you could still find cached page through Google -, that it should be fine to use reflection. Using reflection is perfectly legal if the library writer wants to design the API in such way that the type parameters are not erased. Type parameters are stored inside of the class using class literals. He says that in this case "you can instantiate using reflection (tClass.newInstance()), create arrays (Array.newInstance), cast (Class.cast), and do instanceof tests (Class.isInstance), though with a slightly different syntax than you might prefer".
    I'm still learning generics and I might be wrong.
    Best regards,
    Andrej

  • My generic array creation problem.

    I'm getting a "generic array creation" error on lines 6 and 14. I've googled it and I'm still having a hard time. Most things I find on it are pretty complicated and as you can see mine's not, I'm in a beginners course. I'm basically writing a class with methods for dealing with a file of donors.
    Here's my code:
    public class DonorList <dlist>
        //Create empty list
        public DonorList()
            storage = new dlist [MAX];
            count = 0;
        //Capacity as specified
        public DonorList (int cap)
            MAX = cap;
            storage = new dlist [MAX];
            count = 0;
        public boolean isEmpty()
            return count == 0;
        public void clear()
            count = 0;
        //Returns number of elements
        public int size()
            return count;
        //Item at position k, position starts at zero
        public dlist get (int k)
            if (k >= 0 && k < count)
                return storage [k];
            return null;
        // e becomes item at position k
        public dlist set (int k, dlist e)
            dlist old = null;
            if (k > 0 && k < count)
                    old = storage [k];
                    storage [k] = e;
            return false;
        //Returns the position of e or -1 if not found.
        public int indexOf (dlist e)
            int k;
            for (k = 0; k < count; k++)
                if (e.equals(storage[k]))
                    return k;
            return -1;
        //Appends e at the end of the list. Returns false on failure.
        public boolean append (dlist e)
            if (count < MAX)
                storage [count] = e;
                count ++;
                return true;
            return false;
        //Adds e at position k. Returns false on failure.
        public boolean add (int k, dlist e)
            int j;
            if (count == MAX || k < 0 || k > count)
                return false;
            for ( j = count; j > k; j--)
                    storage [j] = storage [j-1];
                    storage [k] = e;
                    count ++;
                    return true;
            return false;
        private int MAX = 100;
        private dlist [] storage;
        private int count;
    }Any help as to why I am getting these errors is very much appreciated. Thanks.

    You cannot create an array of a generic, instead you need to create an array of the class the generic extends (in this case Object)
    You then have to cast the array to the generic type which will give you an unchecked warning which you can turn off with @SuppressWarning("unchecked") on the class.
    Generics and arrays don't always play nicely together and this is one case. ;-)

  • Tutorial for make a non-generic type class from a generic type interface

    Hi there,
    How can I make a non-generic type class from a generic type interface?
    I appreciate if somebody let me know which site can help me.
    Regards
    Maurice

    I have a generic interface with this signature
    public interface IELO<K extends IMetadataKey>
    and I have implemented a class from it
    public class CmsELOImpl<K extends IMetadataKey> implements IELO<K>, Cloneable, Serializable
    then I have to pass class of an instance CmsELOImpl to AbstractJcrDAO class constructor whit below signature
    public abstract class AbstractJcrDAO<T> implements JcrDAO<T> {
    public AbstractJcrDAO( Class<T> entityClass, Session session, Jcrom jcrom ) {
              this(entityClass, session, jcrom, new String[0]);
    So I have made another class extended from AbstractJcrDAO. Below shows the code of this class and itd constructor
    public class ELODaoImpl extends AbstractJcrDAO<CmsELOImpl<IMetadataKey>> {
         public ELODaoImpl( Session session, Jcrom jcrom ) {
         super(CmsELOImpl.class , session , jcrom, MIXIN_TYPES);
    and as you see in its constructor I am calling the AbstractJcrDAO constructor by supper method
    then I got this error on the line of super method
    The constructor AbstractJcrDAO(class<CmsELOImpl>, session, Jcrom, String[]) is undefined.
    as I know java generics are implemented using type erasure. This generics are only
    in the java source file and not in the class files. The generics are only used by the compiler and
    they are erased from the class files. This is done to make generics compatible with (old) non generics java code.
    As a result the class object of AbstractJcrDAO<CmsELOImpl<IMetadataKey>>
    is AbstractJcrDAO.class. The <CmsELOImpl<IMetadataKey>> information is
    not available in the class file. As far as I understand it, I am looking a way
    to pass <CmsELOImpl<IMetadataKey>>, if it is possible at all.
    Maurice

  • HT2534 in my iphone5 'none' option for credit card is not being appeared. May be because of software upgrade or wot it is really not good as i don't want to share my credit card number.

    the 'none' option under payment methods is not being appeared in my iphone 5 as i don't want to share my credit card info. and my id stuck over that point as i am not abble to skip this step and it is a must option to select a credit card type and give a real credit card details. This is really not good.

    You have to enter your credit card number and some amount would be debited from your account(60 rs in india)
    After registration, You can Go to
    1 Settings
    2.Itunes&App Store
    3.Click on your apple id .
    4.Select View Apple ID
    5.Slecet Payment Info
    And You can find NONE here.
    Please select NONE to delete your credit card numbe r from the list
    But While registering you cant find NONE, you have to enter the cc number.
    Thank You
    Tejas

  • All my prints using: Lightroom 5, printer color management turned off, and non-generic ICC profile (e.g. Epson Premium Glossy) have magenta tint or cast

    I'm using PC with: Windows 8.1, 64bit, Lightroom 5.4, Epson R3000, 6.75 (latest) driver, color management turned off in printer settings, Lightroom configured to manage color.  If I use a generic ICC profile such as Epson sRGB, the prints look OK.  But when I use any ICC profile dedicated to my paper and printer combination, such as Epson Premium Glossy, or one created using ColorMunki print profile, the prints all have a medium to heavy magenta tint or cast.  The effect can be seen before I even print in the Epson Print Preview.  Yet when I soft proof, I don't see this effect.  I suspect the problem lies somewhere in the CMM process, but I can't pin it down.  Any tips or suggestions are appreciated.

    Thank you kindly for your insightful response.  As it turns out, the answer is half correct.  I've found others who'll say the same thing, that double color management will lead to a very magenta result.  I believe this was certainly the case when I first started playing with the settings,  Where I went wrong, is that after I corrected my settings by turning off printer manages color and letting Lightroom do the color management, is that the Epson Print Preview was still showing magenta with certain profiles.  Not wanting to waste more money on paper and ink, I used the preview to gauge whether I was going to get a normal print or not.  Then one day I ignored the print preview's magenta cast as a 'warning' and I went ahead printed the photo anyways.  Because I used a profile that I created with ColorMunki Photo, the picture came out perfect (i.e. a very good match to what I was seeing in Lightoom on my monitor).  The lesson learned is that for judging the final color correctness, the Epson Print Preview can be way off target and your best bet is to ignore it.

  • Array casting: ClassCastException

    import java.util.Vector;
    public class X
    public static void main(String args[])
         //first part
    String [] array = {"1","2", "3"};
    Object [] objs = array;
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array);
         //second part
    Vector v = new Vector();
    v.add("1");
    v.add("2");
    v.add("3");
    objs = v.toArray();
    array = (String[])objs;
    for( int i =0 ; i < array.length; i++)
    System.out.println(array[i]);
    Why does the first part work properly but the second cause ClassCastException? Even if an array was instantiated as Object[] in toArray method casting MUST be ok. I work with an instances in array but not with array. An array only contains an objects I work with. It's only technical structure! Why does it cause ClassCastException?

    >
    Yes. I know it. The point is WHY it was done in this
    way? What can I do with the type of array? NONE. The
    actual information is CONTAINED in array. So array
    is only technical structure. I can't derive it, it has
    no virtual mechanisms. The actual objects I need are
    stored in array. The type of them is important. It
    looks like miss of language structure.
    The basic question here is a fundamental part of polymorphism - you cannot cast an Object into one that it is not.
    Object a = new Object();
    String b = (String) a;That code will also compile, but it is just as incorrect as your code. The problem is that "a" will never be a String. There may be ways to convert it into a String, but the object a will always be of type "Object" and never extend String, so it cannot be cast.
    Similarly, an array of type Object[] will always be of type Object[]. It cannot be cast to String[], because it will never have String[] as a superclass, if you will. The rules for working with arrays are exactly the same as working with the object which is the base type of the array.
    In order to be able to do a cast from Object[] to String[], there would have to be a runtime check which would ensure that every element in the Object[] was, in fact, a String. But the cast check in the compiler is just looking up the extends and implements chains. If you want to implement a runtime cast, Java basically leaves that up to you.
    And as has been mentioned, they do let you provide the array to be used as well.

  • About array cast.

    dear all
    could someone tell me what's wrong with the following codes?
    Object objarr[]
    = {new Integer(1), new Integer(2)};
    Integer[] intarr = (Integer [])objarr;
    it throws out a java.lang.ClassCastException when i ran it. but doesn't the objarr actually represents a Integer array?
    regards
    Yang Liu

    In Java, all objects are by default of Object type. That means an Integer object is of Object type. Similarly a String object is of Object type.
    But if I give you an object of type Object, can u absolutely say whether it is an Integer or a String (ofcourse assuming u don't use relection etc) ? No you cannot..
    Simlarly when you have a Object array, you can put anything into that array, a String or an Integer etc. So u cannot be sure that an Object array always contains only Integer... That is y u get the class cast exception.....
    Ofcourse, this is just the inheritance concept... A BMW is a type of car.. but a car needn't be a type of BMW... it could be a Toyota instead or someting else...
    Integer[] intarr = {new Integer(1), new Integer(2)};
    Object[] objarr = (Object[]) intarr;
    the above code works well.. since all Integer (s) are of Object type in Java....
    Hope this helps

  • WHY IS array CASTING NOT WORKING ?

    data object:
    class myData extends BaseData
    class x
    BaseData[] lData = null;
    setData(BaseData[] aData)
         lData = aData;          
    getData(BaseData[] aData)
    return lData;     
    class y
    myData[] a = new myData[];
    x xx = new x();      
    xx.setData(a);
    xx = (myData[])xx.getData(); <---casting doesnt work !!               
    }

    well IData IS an array so that's not the problem
    The problem is that an array is an object with its own inheritance but it has no knowledge of the inheritance of the objects it contains. So String[] does not extends Object[] even though String extends Object. But all 4 extends Object :)
    run this little to see to what interfaces/classes you can cast your arrays:
    public class Test {
         public static void main(String[] args) {
              Class cl = args.getClass();
              Class[] interfaces = cl.getInterfaces();
              System.out.println( "classes and super-classes" );
              while (cl != null) {
                   System.out.println( "    "+cl );
                   cl = cl.getSuperclass();
              System.out.println( "interfaces" );
              for (int i = interfaces.length; i-->0; )
                   System.out.println( "    "+interfaces[i] );
    }

  • Generic Observer - Casting problems..

    I'm trying to make a generic observer pattern, modeled after Wadler's book.
    But I get type errors at the lines marked with ?? below, and although I fixed them, don't understand why the original code is wrong - any help please!
    interface Observer<S extends Observable<S,O,A>,
                           O extends Observer  <S,O,A>,
                           A > {
         public void update ( S subject, A arg);
         // public void update ( Observable<S,O,A> subject, A arg);
    abstract class Observable<S extends Observable<S,O,A>,
                                 O extends Observer  <S,O,A>,
                                 A > {
         List<Observer<S,O,A>> obs = new ArrayList<Observer<S,O,A>>();
         boolean changed = false;
        public void          notifyObservers(A a){
             // for ( O o : obs )            // ??
             //    o.update(this,a);          // ??
             for ( Observer<S,O,A> o : obs )
                  o.update((S)this,a );     // Cast??
    }

    Stephan,
    To illustrate the problem with your version and a client;
    The type TestObsGen must implement the inherited abstract method Observer<Thing,TestObsGen,Integer>.update(Observable<Thing,TestObsGen,Integer>, Integer)
    Any insights welcome!
    public interface Observer<
         S extends Observable<S, O, A>,
         O extends Observer<S, O, A>,
         A> {
        public void update(Observable<S, O, A> subject, A arg);
    abstract class Observable<
                   S extends Observable<S, O, A>,
                   O extends Observer<S, O, A>,
                   A> {
        List<Observer<S, O, A>> obs = new ArrayList<Observer<S, O, A>>();
        boolean changed = false;
        public void notifyObservers(A a) {
            for (Observer<S, O, A> o : obs)
                o.update(this, a);
    public class TestObsGen
         implements Observer< Thing, TestObsGen, Integer >
         Thing thing;
         TestObsGen ( Thing t ) {
              thing = t;
              // t.addObserver(this);
         void update(Thing t, Integer count) {
              System.out.println("Count:" + count);
         public static void main(String[] args) {
              Thing t = new Thing();
              TestObsGen test = new TestObsGen(t);
              t.bump();
              // Event received?!
    class Thing
         extends Observable< Thing, TestObsGen, Integer >
         int count;
         void bump() {
              count++;
              // setChanged();
              // notifyObservers();
    }

  • Array Casting in java

    Hi,
    I am new to java.Last day Can I cast an arrays in java?For example casting an Object array to a String array or an integer array to a long one.If yes, then what are the rules and restrictions for casting arrays.I tried to google it, but I could not find any useful material.Could any one give me some links where I can get some useful material,books,mock tests etc. regarding preparation for SCJP 1.6?.Please help.
    Thanks in advance

    This is the Berkeley DB, Java Edition forum, and you should post only post questions about that product here. I think you may be looking for basic Java language information, and there are many other websites that can give you that information.

  • Array Cast Question Puzzling me

    The question below puzzles me. The answer states that the result is a class cast exception because o1 is an int [] [] not a int []
    But I thought the point of line 7 is to say "I know it is a 2D array but I want to cast it to a 1D array - I know I am losing precision here".
    Given:
    1. class Dims {
    2. public static void main(String[] args) {
    3. int[][] a = {{1,2,}, {3,4}};
    4. int[] b = (int[]) a[1];
    5. Object o1 = a;
    6. int[][] a2 = (int[][]) o1;
    7. int[] b2 = (int[]) o1;
    8. System.out.println(b[1]);
    9. } }
    What is the result?
    A. 2
    B. 4
    C. An exception is thrown at runtime
    D. Compilation fails due to an error on line 4.
    E. Compilation fails due to an error on line 5.
    F. Compilation fails due to an error on line 6.
    G. Compilation fails due to an error on line 7.
    Answer:
    3 C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][]
    not an int[]. If line 7 was removed, the output would be 4.
    &#730; A, B, D, E, F, and G are incorrect based on the above. (Objective 1.3)

    While you could approximate casting a 2D array to a 1D array in C/C++ by just grabbing a pointer to your first array and then overrunning array bounds (relying on how C/C++ allocates 2D arrays and the lack of bounds checking), Java's strong typing and bounds checking makes this impossible.
    If you want to do something similar in Java, you will need to create a new 1D array of the proper size and copy the elements stored in your 2D array into this new array. That being said, a database is almost guaranteed to be a better solution.

  • Best Way to Enumerate a non-unique Array of String to Integers

    Hello,
    I am trying to find the best way to enumerate an array of strings to integers. This string array is thousands in number and contains non-unique values.
    I also don't know before run-time what those values are, so I have to dynamically determine the enumeration.
    For example a user reads in an array of colors (but we didnt know this before runtime) of "red", "green", "red", "blue", "white", "green", "black", "blue"
    I would like this to enumerate to 0, 1, 0, 2, 3, 1, 4, 2
    as zero based enumeration.
    Is there any suggested methods of doing this as efficiently on SPEED over MEMORY as possible?
    Thanks!
    Glenn

    I also don't know before run-time what those values are, so I have to dynamically determine the enumeration.Are you saying that you can't pre-define the universe of colors that a user could potentially enter? If so, how will you determine the equivalence of RED to 0, etc? That sounds suspicious, there is a finite number of colors!
    Anyway, for what it's worth, here's some code (that requires you know the color labels that could be entered.)
    enum Color
        RED(0), GREEN(1), BLUE(2), BLACK(3), WHITE(4);
        private final int colorValue;
        private Color(int colorValue)
            this.colorValue = colorValue;
        public int getColorValue()
            return colorValue;
    public class EnumTest
        public static void main(String[] args)
            System.out.println(Color.RED + " = " + Color.RED.getColorValue());
            System.out.println(Color.GREEN + " = " + Color.GREEN.getColorValue());
            System.out.println(Color.BLUE + " = " + Color.BLUE.getColorValue());
            System.out.println(Color.BLACK + " = " + Color.BLACK.getColorValue());
            System.out.println(Color.WHITE + " = " + Color.WHITE.getColorValue());
    }

  • Generic array deletion & insertion

    Hello,
    I was going through the options the generic Vector class offers to delete and/or insert items from/to an array, and it seems to me that the only way is by using the Splice method. For me, this method does a lot of work I dont utilize in my code (like creating a new array as a result etc.), hence
    is there an optimized way how to delete a certain item from a vector, instead of calling myVector.splice(idItemToRemove,1) ?
    Thanks for any answer!
    Tom

    that's it for array removal.  push() would be the usual method for adding elements

  • Dealing With Non Uniform Array Sizes

    Would it be possible to store data such as
    1 2 3 4 5 6
    0 2 4
    3 1 4 1 5 9 2 6 5 3 5 8 9
    Where each row is not nessicarly the same length. I need to later call a specific row by row number and plot the 1D array. I have figured out arrays wont deal with the non uniform length and will instead fill in the extra elements so they all match in length. Is there any way around this?
    Thanks

    It is generally better to use Repalce Array Subset or autoindexing to build an array. Insert into Array may cause memory allocation problems. Here are two mnodifications to your VI which show both methods. If you need to see the results as you go, the Replace Array Subset is best. If you do not need the data until the for loop completes, autoindexing is the preferred choice.
    Note that you may need to initialize your shift register. Run the VI multiple times and watch the results.
    Lynn
    Attachments:
    Variable Length Arrays.2.vi ‏15 KB

Maybe you are looking for

  • Mac OS 10.4 Address Book Contacts

    Niether the Palm Data Transfer Agent nor the MissingSync program work under Mac OS 10.4, and I do not want to pay for 10.5 when 10.6 is coming out in September.  Here is how I have found to copy all of my Address Book contacts to the Pre.  It require

  • Insufficient data for image (9-9.3) or a blank page (8.1)

    Hi, We recently started using a Xerox workcenter 5675 to scan document to my central server. About 3 days ago users started reporting an error message with a white page. I immediately checked the copier, nothing changed setting wise. It has been full

  • Precise positioning/move of gradient annotator?

    Hello, when one has selected an object and assigned a gradient fill, and after pressing G to select the gradient tool, the X and Y coordinates correspond the location of the shape, not the location of the gradient.  Meaning, even if I know the coordi

  • Query related to Nexus Affected by Shell Shock

    Hi Can anyone please tell us if the below Nexus hardware with the respective software (NX-OS) is affected by shell shock ? If yes then which is the fixed version of NX-OS for each ? Thanks in advance. Regards, Nasir 

  • MRP type V1

    Dear All, Please let me know the settings in material master for MRP type V1. I have enetred lot size as MB. Minimum lot size 200, reorder point 100. After MRP run we received purchase requisistion of 200. Then we created sales order due to which now