Ok, so here's a small problem I'm facing - is there an easy way in Java to cast
ArrayList<Object[]> array;
to
Object[][] data;
?
Object[][] data=array.toArray();
The Object[]'s inside are treated as a type of object themselves. They then are put into their own array, leading to an array of array objects of objects, or simply a two-dimensional array.
Casting is not the solution you are looking for. Casting would essentially allow you to use a method that you cast to a specific class type. An example of a cast:
(((ClassA)classB).method())
So a returned value can be placed inside of a ClassA object from the instantiated classB object that contains method().
What you are wanting to do on the other hand is create a multidimensional array or a 2D array. This is essentially an array of arrays, where arrayA[i] = arrayB[];
For example:
Object[] objectArray = new Object[5];
Object[][] = objectArray2D = new Object[][];
objectArray2D[i] = objectArray;
Here is a point to your question though, if you create a multidimensional array, why would you feed it only one array instance. Essentially what you would create in the above example is an array inside of an array, and since you will be giving it only 1 array indexing of all the objects inside the array would be the same as if you had the one array, but with one additional placement. Let me explain:
objectArray[0] == the object you placed on the first slot of objectArray
while objectArray2D[0][0] == the exact same object as the object in objectArray[0]
You are not receiving any advantage by using a multidimensional array for one array. If you were to ask the 2D array for the index [1][0] you would receive an out of bounds exception.
Lastly, I would suggest that you create a specific form of array, such as int[], or string[]. The problem with a Object[] array is that you can store anything that is considered an Object into the array, allowing for a potential cluster of different types of Objects inside one array. Example you could have a objectArray[0] = int 1; and objectArray[1] = String one; Unless you want to be very specific in the array use, it might be better to use one Object type as the array.
In any case the final solution to do exactly what you are wanting to do is as follows:
ArrayList<Object[]> array;
Object[][] data;
public void changeToAnArray(ArrayList<Object[]> array, Object[][] data)
{
this.array = array.toArray();
this.data[0] = array;
}
Also due note the point of an ArrayList, is to have a 2D array in essence without having to parse the indexes.
Please anyone feel free to correct on the parts I am wrong on << still learning.
Related
I am trying to understand some fundamentals about arrays. I thought multidimensional arrays were really just arrays of arrays. With that in mind, I don't understand the following behavior:
Object [] object = {new Object[1]};
Object anotherObject = object[0][0]; //doesn't work
Object yetAnotherObject = object[0]; //does work
I am confused why the second line does not compile ("Array type expected"). I thought since "object[0]" was in fact an object array, I could use the square brackets to access its contents.
What am I missing?
The type of object is Object[], which is a 1 dimensional array. The fact that you store an array element in that array doesn't make it a 2 dimensional array.
Object anotherObject = object[0][0];
doesn't work since the compiler doesn't know that object[0] is an array (and it doesn't have to be - object[0] can hold a reference to any Object).
You'll need casting in order for it to work:
Object anotherObject = ((Object[])(object[0]))[0];
I want to build a 2D array from N (one-dimensional) arrays. The only problem is, as far as I can tell, the only way to declare a multi-dimensional array in Java requires you to specify all inner dimension sizes, and those sub-arrays get created. In this case, this seems wasteful, since they will be overwritten
In C++, I could do this:
Object** arr = new Object*[n];
for(int i=0;i<n; ++i)
{
arr[i] = getObjArr();
}
In Java, you have to say this:
Object[][] arr = new Object[n][0]; //inner dimension is required
Each of those n zero-length arrays will be created, only to get overwritten as the array is populated. Is there a way to declare a multi-dimensional array (similar to the pointer to pointer(s) syntax of C) without allocating the inner arrays?
Sure. I don't know why you think you have to do that!
double[][] foo = new double[2][];
is perfectly fine. The "inner" arrays will be null.
Inner dimensions do not have to be specified. This is legal in Java:
Object[][] arr = new Object[n][];
This creates an array of n elements, where each element has type Object[]. Since you did not specify an inner dimension, those n elements are all initialized to null. You can then assign any Object[] you want to any of those n array elements.
For higher-dimensional arrays, the rule (if you don't have an initializer) is that you can say new T followed by one or more specified dimensions ([some-value]), followed by zero or more [] for unspecified dimensions. You can't have [] followed by [value].
I have this method getData as shown .
It is expecting an array of bag Objects as shown
please see the code below :
public static String getData(Bag[] bag)
{
}
public class Bag
{
public char side;
}
But , when i tried i am getting ClassCastException .
I have done this way :
Object bagArray[] = new Object[1];
Bag bagData = new Bag();
bagData.side = 'S';
bagArray[0]=bagData;
String bagData = ApplicationUtil.getData(Bag[]) bagArray);
Please let me , how to resolve this error ??
Why are you creating an Object array rather than an array of Bag objects?
Try just changing the first line to Bag[] bagArray = new Bag[1].
As an Object array can hold any kind of object, so I don't think it can be cast to a Bag array. You could however cast bagArray[0] to a Bag object.
In future, try using a List or other collection rather than an array for stuff like this.
The problem is that bagArray is an array of Object and not an array of Bag.
Either change that to Bag bagArray[] = new Bag [1]; or use a Collection (e.g. List) instead - note that you can cast List<Object> to List<Bag> but that is an unsafe operation and not recommended unless you know what you're doing.
You're trying to cast an Object[] into a Bag[]. Not allowed.
You bagArray is an Object array and not a Bag array. Just because it is capable of holding an object of type Bag (which is a subclass of Object), does not mean the vice versa. You are trying to cast Object to Bag type, which is not allowed. Define you bag array in the following way
Object bagArray[] = new Bag[];
See this question: Quick Java question: Casting an array of Objects into an array of my intended class
As others have said, you can't cast an Object[] to, well, anything. In this case, you have a Bag inside an Object array, so in this specific instance it seems like it might work. But imagine that you had a larger array, full of objects of different types. In that case, the cast wouldn't work. The program has to work for the general case.
You can solve this by:
1) Using a Bag[] type instead of Object[]
2) Using a List - collections are nearly always better
3) Using the Arrays class to create a new Bag[]: Arrays.copyOf(bagArray,bagArray.length,Bag[].class)
This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 8 years ago.
I'm working in the android environment and have tried the following code, but it doesn't seem to be working.
String [] stockArr = (String[]) stock_list.toArray();
If I define as follows:
String [] stockArr = {"hello", "world"};
it works. Is there something that I'm missing?
Use like this.
List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");
String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Try this
String[] arr = list.toArray(new String[list.size()]);
What is happening is that stock_list.toArray() is creating an Object[] rather than a String[] and hence the typecast is failing1.
The correct code would be:
String [] stockArr = stockList.toArray(new String[stockList.size()]);
or even
String [] stockArr = stockList.toArray(new String[0]);
For more details, refer to the javadocs for the two overloads of List.toArray.
The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)
From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray() method has no information of what the <T> is at runtime. All it knows is that the raw element type is Object. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)
1 - In Java, an Object[] is not assignment compatible with a String[]. If it was, then you could do this:
Object[] objects = new Object[]{new Cat("fluffy")};
Dog[] dogs = (Dog[]) objects;
Dog d = dogs[0]; // Huh???
This is clearly nonsense, and that is why array types are not generally assignment compatible.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray wasn't changed to T[] toArray where generics ware introduced to Java.
Why String[] stockArr = (String[]) stock_list.toArray(); wont work?
In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>) is removed and replaced with Object type (take a look at type erasure). That is why at runtime toArray() have no idea about what precise type to use to create new array, so it uses Object as safest type, because each class extends Object so it can safely store instance of any class.
Now the problem is that you can't cast instance of Object[] to String[].
Why? Take a look at this example (lets assume that class B extends A):
//B extends A
A a = new A();
B b = (B)a;
Although such code will compile, at runtime we will see thrown ClassCastException because instance held by reference a is not actually of type B (or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B could have new methods/fields which A doesn't, so it is possible that someone will try to use these new members via b reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.
You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a reference, and there is a chance that it will hold instance of class B which will support interface of b reference. Take a look at this example:
A a = new B();
// ^------ Here reference "a" holds instance of type B
B b = (B)a; // so now casting is safe, now JVM is sure that `b` reference can
// safely access all members of B class
Now lets go back to your arrays. As you see in question, we can't cast instance of Object[] array to more precise type String[] like
Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown
Here problem is a little different. Now we are sure that String[] array will not have additional fields or methods because every array support only:
[] operator,
length filed,
methods inherited from Object supertype,
So it is not arrays interface which is making it impossible. Problem is that Object[] array beside Strings can store any objects (for instance Integers) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3) on instance of Integer which doesn't have such method.
So to make sure that this situation will never happen, in Java array references can hold only
instances of array of same type as reference (reference String[] strArr can hold String[])
instances of array of subtype (Object[] can hold String[] because String is subtype of Object),
but can't hold
array of supertype of type of array from reference (String[] can't hold Object[])
array of type which is not related to type from reference (Integer[] can't hold String[])
In other words something like this is OK
Object[] arr = new String[] { "ab", "cd" }; //OK - because
// ^^^^^^^^ `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as
// reference
You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look
//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());
now most common type is B, not A so toArray()
A[] arr = elements.toArray();
would return array of B class new B[]. Problem with this array is that while compiler would allow you to edit its content by adding new A() element to it, you would get ArrayStoreException because B[] array can hold only elements of class B or its subclass, to make sure that all elements will support interface of B, but instance of A may not have all methods/fields of B. So this solution is not perfect.
Best solution to this problem is explicitly tell what type of array toArray() should be returned by passing this type as method argument like
String[] arr = list.toArray(new String[list.size()]);
or
String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.
The correct way to do this is:
String[] stockArr = stock_list.toArray(new String[stock_list.size()]);
I'd like to add to the other great answers here and explain how you could have used the Javadocs to answer your question.
The Javadoc for toArray() (no arguments) is here. As you can see, this method returns an Object[] and not String[] which is an array of the runtime type of your list:
public Object[] toArray()
Returns an array containing all of the
elements in this collection. If the collection makes any guarantees as
to what order its elements are returned by its iterator, this method
must return the elements in the same order. The returned array will be
"safe" in that no references to it are maintained by the collection.
(In other words, this method must allocate a new array even if the
collection is backed by an Array). The caller is thus free to modify
the returned array.
Right below that method, though, is the Javadoc for toArray(T[] a). As you can see, this method returns a T[] where T is the type of the array you pass in. At first this seems like what you're looking for, but it's unclear exactly why you're passing in an array (are you adding to it, using it for just the type, etc). The documentation makes it clear that the purpose of the passed array is essentially to define the type of array to return (which is exactly your use case):
public <T> T[] toArray(T[] a)
Returns an array containing all of the
elements in this collection; the runtime type of the returned array is
that of the specified array. If the collection fits in the specified
array, it is returned therein. Otherwise, a new array is allocated
with the runtime type of the specified array and the size of this
collection. If the collection fits in the specified array with room to
spare (i.e., the array has more elements than the collection), the
element in the array immediately following the end of the collection
is set to null. This is useful in determining the length of the
collection only if the caller knows that the collection does not
contain any null elements.)
If this collection makes any guarantees as to what order its elements
are returned by its iterator, this method must return the elements in
the same order.
This implementation checks if the array is large enough to contain the
collection; if not, it allocates a new array of the correct size and
type (using reflection). Then, it iterates over the collection,
storing each object reference in the next consecutive element of the
array, starting with element 0. If the array is larger than the
collection, a null is stored in the first location after the end of
the collection.
Of course, an understanding of generics (as described in the other answers) is required to really understand the difference between these two methods. Nevertheless, if you first go to the Javadocs, you will usually find your answer and then see for yourself what else you need to learn (if you really do).
Also note that reading the Javadocs here helps you to understand what the structure of the array you pass in should be. Though it may not really practically matter, you should not pass in an empty array like this:
String [] stockArr = stockList.toArray(new String[0]);
Because, from the doc, this implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). There's no need for the extra overhead in creating a new array when you could easily pass in the size.
As is usually the case, the Javadocs provide you with a wealth of information and direction.
Hey wait a minute, what's reflection?
String[] a = c.toArray(new String[0]);
First: Do I need type cast here? (I think we should write like (String[])c.toArray(); BUT I have seen it as just c.toArray() without using type cast. Is this valid?
Second: Also why we write new String[0]?
The type cast is usually only needed if you're using pre-generics Java. If you look at the docs for Collection.toArray(T[]) you'll see that it knows that the type of the array which is returned is the same as the type of array passed in. So, you can write:
List<String> list = new ArrayList<String>();
list.add("Foo");
String[] array = list.toArray(new String[0]);
You pass in the array to tell the collection what result type you want, which may not be the same as the type in the collection. For example, if you have a List<OutputStream> you may want to convert that to an Object[], a Stream[] or a ByteArrayOutputStream[] - obviously the latter is only going to work if every element actually is a ByteArrayOutputStream. It also means that if you already have an array of the right type and size, the contents can be copied into that instead of creating a new array.
A previous version of this answer was inaccurate, by the way - if you use the overload which doesn't take any parameters, you always get back an Object[] which can't be cast:
List<String> list = new ArrayList<String>();
list.add("Foo");
// toArray doesn't know the type of array to create
// due to type erasure
Object[] array = list.toArray();
// This cast will fail at execution time
String[] stringArray = (String[]) arrray;
EDIT: I've just noticed this is also mentioned in erdemoo's answer, but it can't hurt to have it here too :)
if you are using list.toArray(), it will return you Object array.
Casting to String array will throw exception even if elements stored in list are String type.
if you are using list.toArray(Object[] a), it will store elements in list to "a" array. If the elements inside the list are String and you give String array then it will store elements inside String array, if given array is not large enough to store elements inside the list, then it will expand given list.
Yes you need the downcast since toArray's returns type is Object[].
You need to pass (new String[0]) as a parameter since the method needs to know what kind of array it should return (array of strings, Dates, etc.) Internally all list elements are actually objects so the list does not know the type of elements it is holding and therefore it does not know which kind of array it should return, unless you provide it as a parameter.