Wednesday, January 25, 2017

java: generic array creation error

The line of code below incurs a generic array creation error at compile time.

       ArrayList<String>[] sc = new ArrayList<String>[2];

The following code compiles, but it will generate an unchecked cast warning at compile time.

      ArrayList<String>[] sc = (ArrayList<String>[]) new Object[2];

However, if you cast an already built Object array to an ArryList<String>[] and if the array contains object other than ArrayList<String> a ClassCastException will happen at execution time.

        Object[] test = new Object[2];
        test[0] = new ArrayList<String>();
        test[1] = new Integer(9);
        ArrayList<String>[] sc = (ArrayList<String>[])test;

The following code compiles, but gives an unchecked cast warning at compile time. If you don't want to see the warning message, you can supress it.

      @SuppressWarnings("unchecked")
      ArrayList<String>[] sc = (ArrayList<String>[])Array.newInstance(String.class, 2);
or
      ArrayList<String>[] sc = (ArrayList<String>[]) new ArrayList[2];

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment