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

  • Home
  • SEARCH
  • 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 3761680
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T10:39:48+00:00 2026-05-19T10:39:48+00:00

A difficult question which I’m close to giving up all hope on. I’m trying

  • 0

A difficult question which I’m close to giving up all hope on. I’m trying to make a
function, but am having problems getting ArrayList.toArray() to return the type I want.

Here’s the minimal example that demonstrates my problem:

public static <T> T[] test(T one, T two) {
    java.util.List<T> list = new ArrayList<T>();
    list.add(one);
    list.add(two);
    return (T[]) list.toArray();
}

Normally I’d be able to use the form (T[]) list.toArray(new T[0]) but there are two added difficulties:

  1. Because of the covariance rules I cannot typecast arrays, (T[]) myObjectArray gives a ClassCastException
  2. You cannot create a new instance of a generic type, meaning I cannot instance new T[]. Nor can I use clone on one of the elements of ArrayList or try to get its class.

I’ve been trying to get some information using the following call:

public static void main(String[] args) {
   System.out.println(test("onestring", "twostrings"));
}

the result is of the form [Ljava.lang.Object;@3e25a5 suggesting that the typecast on the return is not effective. strangely the following:

public static void main(String[] args) {
    System.out.println(test("onestring", "twostrings").getClass());
}

comes back with:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at patchLinker.Utilities.main(Utilities.java:286)

So my best guess is that it think’s it’s a String array label wise, but internally is an Object array, and any attempts to access brings that inconsistancy out.

If anyone can find any way of working around this (since the two normal workarounds are denied to me) I’d be very greatful.

K.Barad
JDK1.6


Edit


Thanks to Peter Lawrey for solving the initial problem. Now the issue is how to make the solution apply to my less trivial example:

public static <T> T[] unTreeArray(T[][] input) {
    java.util.List<T> outList = new ArrayList<T>();
    java.util.List<T> tempList;
    T[] typeVar;
    for (T[] subArray : input) {
        tempList = java.util.Arrays.asList(subArray);
        outList.addAll(tempList);
    }
    if (input.length > 0) {
        typeVar = input[0];
    } else {
        return null;
    }
    return (T[]) outList.toArray((T[]) java.lang.reflect.Array.newInstance(typeVar.getClass(),outList.size()));
}

public static void main(String[] args) {
    String[][] lines = { { "111", "122", "133" }, { "211", "222", "233" } };
    unTreeArray(lines);
}

The result at the moment is

Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(Unknown Source)
at patchLinker.Utilities.unTreeArray(Utilities.java:159)
at patchLinker.Utilities.main(Utilities.java:301)

I’m still doing some tests to see if I can get any more useful information than this, but at the moment I’m not sure where to start. I’ll add any more information I get as I get it.

K.Barad


edit 2


Some more information now. I’ve tried to build the array manually and transfer the items in elementwise, so I’d be typecasting as T, rather than T[]. I found an interesting result:

public static <T> T[] unTreeArray(T[][] input) {
    java.util.List<T> outList = new ArrayList<T>();
    java.util.List<T> tempList;
    T[] outArray;
    for (T[] subArray : input) {
        tempList = java.util.Arrays.asList(subArray);
        outList.addAll(tempList);
    }
    if (outList.size() == 0) {
        return null;
    } else {
        outArray = input[0];// use as a class sampler
        outArray =
                (T[]) java.lang.reflect.Array.newInstance(outArray.getClass(), outList.size());
        for (int i = 0; i < outList.size(); i++) {
            System.out.println(i + "  " + outArray.length + "   " + outList.size() + "   "  + outList.get(i));
            outArray[i] = (T) outList.get(i);
        }
        System.out.println(outArray.length);
        return outArray;
    }
}

I still get the following output:

0  6   6   111
Exception in thread "main" java.lang.ArrayStoreException: java.lang.String
at patchLinker.Utilities.unTreeArray(Utilities.java:291)
at patchLinker.Utilities.main(Utilities.java:307)

Does this mean you can’t write to a T[] even if you manage to create one indirectly?

  • 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-19T10:39:49+00:00Added an answer on May 19, 2026 at 10:39 am

    The problem on your second code sample is caused because of your T[] typeVar: Input is a two dim array, so input[0] will return a one dim array (a String[], instead a String, as expected).

    If your are to convert your List<T> to a T[], you’ll need a T typeVar,

    To fix it:

    public static <T> T[] unTreeArray(T[][] input) {
        java.util.List<T> outList = new ArrayList<T>();
        java.util.List<T> tempList;
    
        if (input.length == 0) {
            return null;
        }
    
    
        T typeVar=null;
        for (T[] subArray : input) {
            if(typeVar==null && subArray.length>0) {
                typeVar=subArray[0];
            }
            tempList = java.util.Arrays.asList(subArray);
            outList.addAll(tempList);
        }
    
        return outList.toArray((T[]) Array.newInstance(typeVar.getClass(),0));
    }
    
    public static void main(String[] args) {
        String[][] lines = { { "111", "122", "133" }, { "211", "222", "233" } };
        String[] result=unTreeArray(lines);
    
        System.out.println(result);
    
        System.out.println(result.getClass());
    
            //added for completion:
        System.out.println( Arrays.toString(result));
    
    }
    

    The resulting output:

    [Ljava.lang.String;@5a405a4 class
    [Ljava.lang.String;
    [111, 122, 133, 211, 222, 233]

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

Sidebar

Related Questions

I have a simple question which propably has a difficult answer, but what is
This is a difficult and open-ended question I know, but I thought I'd throw
This seems like a simple question, but it is difficult to search for. I
Forgive me if this is a tried question, but I'm having a little difficulty
This is such a difficult question to explain online but I shall try my
I don't think my question is difficult but I'm just a newbie in web
I thought this could've been a common question, but it has been very difficult
This is related to another question of mine, and unfortunately I'm having a difficult
Here with another question on Images ( which seems to be more difficult than
I've been looking for the answer to this question but it seems quite difficult

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.