Sign in to follow this  
cpp_boy

[java] Problems with Array class ...

Recommended Posts

Hello. How can I create an object of Array class. This is an error: Array arr = new Array(); //Array has private access in java.lang.reflect.Array

Share this post


Link to post
Share on other sites
The Array class provides helper functions to work with arrays. This class is not meant to be instantiated.

To create a new array of a type, say char, write this:
char[] myArray = new char[4711];

Then you can use it in another function like this:
... func(Object[] array) throws IllegalArgumentException
{
char c = java.lang.reflect.Array.getChar(array, 3);
...
}

Share this post


Link to post
Share on other sites
Quote:
Original post by nmi
The Array class provides helper functions to work with arrays, since arrays don't provide them.

To create a new array of a type, say char, write this:
char[] myArray = new char[4711];


I'm sorry, but you are wrong. You can create Array class object. Its suppost to be an universal array wich is working with all kinds of objects and primitive types.
There is a method for creatig Array class object, but I cant figure out how it works : Array.newInstance(Class type, int length)

The problem is that I get Class type, and my method must return Array type.
So I tried: return (Array)arr; //inconvertability !!!

Share this post


Link to post
Share on other sites
Quote:
Original post by cpp_boy
I'm sorry, but you are wrong. You can create Array class object. Its suppost to be an universal array wich is working with all kinds of objects and primitive types.
There is a method for creatig Array class object, but I cant figure out how it works : Array.newInstance(Class type, int length)


The constructor of Array is private, so you cannot instanciate the class Array. Its also not supposed to be an universal array, since Object[] does this job. (You can put integral types like int or char into an Object[] by using java.lang.Integer, etc.)

The method newInstance can be used to create arrays of an unknown type.

So instead of writing
String[] myArray = new String[4711];
you could write
String[] myArray = Array.newInstance(String.class, 4711);

That also works if the function accepts the type as parameter:

public Object createArray(Class componentType)
{
return Array.newInstance(componentType, 4711);
}

Then use it like this:

String[] myStrings = (String[])createArray(String.class);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this