0

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 ??

  • 2
    The code as you have posted it wont compile, as the line `String bagData = ApplicationUtil.getData(Bag[]) bagArray);` is missing an opening parenthesis. – nfechner Oct 25 '11 at 11:02
  • Also: Please post the exception (with a reference for the line number in it) and the code for `ApplicationUtil.getData()`. – nfechner Oct 25 '11 at 11:05

5 Answers5

2

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.

Adrian Mouat
  • 44,585
  • 16
  • 110
  • 102
0

You're trying to cast an Object[] into a Bag[]. Not allowed.

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97
0

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[];
Satadru Biswas
  • 1,555
  • 2
  • 13
  • 23
0

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

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)

Community
  • 1
  • 1
Trasvi
  • 1,207
  • 1
  • 15
  • 23