Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6696383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T06:20:06+00:00 2026-05-26T06:20:06+00:00

This question has to do with type erasure and its implication on arrays SCJP

  • 0

This question has to do with type erasure and its implication on arrays SCJP (by Mughal – 3rd edition on page 726). Here’s the code in short:

public class MyStack<E> implements IStack<E> {
    // Top of stack.
    private Node<E> tos;
    // Size of stack
    private int numOfElements;

    :

    // Incorrect version
    public E[] toArray3() {
        E[] toArray = (E[])new Object[numOfElements];
        int i=0;
        for (E data : this) {
           toArray[i++] = data;
        }
        return toArray;
    }

    // Correct version
    public E[] toArray4(E[] toArray) {
        if (toArray.length != numOfElements) {
            toArray = E[])java.lang.reflect.Array.newInstance(toArray.getClass().getComponentType(), numOfElements);
        }
        int i=0;
        for (E data : this) {
             toArray[i++] = data;
        }
        return toArray;
    }
}

According to the book, method toArray3 is the incorrect version to use while method toArray4 is the correct version since array is of reifiable type. I don’t have problem on this. However, I have a problem when it comes to understanding why type parameter E is different for toArray3 and toArray4.

Here’s how I found out. Supposedy I have the following:

MyStack<Integer> intStack = new MyStack<Integer>();
intStack.push(9);
Integer[] x = intStack.toArray4(new Integer[0]); // clause 1
System.out.println(x.length);
Integer[] y = intStack.toArray4(new Object[0]); // clause 2  - compiler error
System.out.println(y.length);
Integer[] z = intStack.toArray3(); // clause 3
System.out.println(z.length);

a. For clause 1, no problem. The type parameter E in toArray4 seems to be of Integer.

b. For clause 2, the error is saying that Integer[] is not applicable for Object[]. Does that mean that type erasure of toArray4(E[] toArray) is toArray4[Integer[] toArray)? Why not Object[]? (Though I know that intStack has been instiantiated with Integer.)

c. For clause 3, the runtime error is that saying Object[] cannot be assigned to Integer[]. I do understand this, but why now is the type parameter E on toArray3 Object and not Integer?

I would expect the type parameter E ON toArray3 to be the same as toArray4 since type parameter E itself for intStack is of integer type which are used by both toArray3 AND toArray4.

Please bear in mind that in the body of toArray3, the array Object has been cast back to E[].

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T06:20:07+00:00Added an answer on May 26, 2026 at 6:20 am

    The difference between these methods is that toArray4() is using reflection to obtain the Class object that represents the correct component type of the array. This ensures that the type information is known at runtime in spite of type erasure.

    The key is this line of toArray4():

    Array.newInstance(toArray.getClass().getComponentType(), numOfElements);
    

    Unlike generic objects, arrays can provide their component type, since something like Integer[] has a corresponding Class object that can be inspected for this information.

    Because of this, toArray4() actually instantiates an Integer[] object when E is Integer, whereas toArray3() instantiates an Object[] and the calling code (through type erasure) attempts to cast it to Integer[], rightly causing a ClassCastException.

    In general, reflection is often used as a workaround to type erasure.

    As a note, arrays in Java tend to have certain “magic” associated with them, especially with regard to reflection. For example if you look at the source for Class#getComponentType() and Array.newInstance() they both lead to native code.

    EDIT: I think the source of your confusion is the cast being done in toArray3():

    E[] toArray = (E[])new Object[numOfElements];
    

    This is not the cast that is causing your ClassCastException. Rather it’s a second cast which is added by type erasure. To illustrate, let’s rewrite toArray3() as if type erasure had been applied:

    public Object[] toArray3() {  
       Object[] toArray = new Object[numOfElements]; //first cast no longer necessary
       int i=0;  
       for (Object data : this) {  //pretend MyStack is no longer generic
          toArray[i++] = data;  
       }  
       return toArray;  
    }
    

    Then in the calling code:

    Integer[] z = (Integer[])intStack.toArray3(); //ClassCastException
    

    As you can see, the ClassCastException is thrown not in the method, but when its result is assigned to z using a cast, which type erasure creates for you. We might verify this if you actually post the stacktrace.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know this question has been asked here before, but I don't think those
I know many times this question has been posted over here. But i am
I know this type of question has been asked before, but I could not
This question has been asked on here a few times, but none of the
This question has been asked before ( link ) but I have slightly different
This question has been discussed in two blog posts ( http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/ , http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/ ),
This question has spawned out of this one. Working with lists of structs in
This question has been asked in a C++ context but I'm curious about Java.
This question has been puzzling me for a long time now. I come from
This question has in the back of my mind for some time, sorry if

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.