English 中文(简体)
解决本法典中的阶级观念
原标题:Resolving ClassCastException in this code
  • 时间:2011-10-25 11:00:19
  •  标签:
  • java

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);

请让我,如何解决这一错误?

最佳回答

问题是<条码>bagArray是一系列<条码>。 目标,而不是一系列<代码> Bag 。

改写如下:<条码>BagpoArray[] = 新的B ? 或使用<条码> >Collection(例如<条码>List ;Object> to List<Bag>,但 系不安全操作,除非你知道什么,否则不建议

问题回答

为什么你们制造一个目标阵列而不是一系列的巴方物体?

Try Just changing the first line to Bag[]po Array = new Bagl.

作为<条码> 反对: 阵列可以持有任何种类的物体,因此我认为它可以投到<条码>。 但是,请将<条码>bagArray[0]至<条码>。

今后,尝试使用清单或其他收集材料,而不是像这样的阵列。

页: 1 不允许。

Youpo Array是一个目标阵列,而不是一个Bag阵列。 仅仅因为能够持有一种“B”类物体(即“反对”的子类),也不意味着反之。 你试图对Bag类提出反对,不允许这样做。 用以下方式界定你袋子阵列:

Object bagArray[] = new Bag[];

见这一问题:。 快速反应 Java问题: 将一系列物体注入我的预定类别

正如其他人所说的那样,你可以提出反对。 在此情况下,你在目标阵列内有一个巴方,因此在这种具体情况下,你似乎喜欢工作。 但是,想象你们有较大的阵容,有各种各样的物体。 在此情况下, cast木工作。 该方案必须处理一般案件。

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)





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...