[英]java : Class cast exception
我有一个包含字符串和tupleList的地图。 我试图让tupleList成为双数组,但我得到了类型转换异常。 我的代码是 -
Map<String, TupleList> results = null; -- Some data in it and TupleList has int or double value.
public void drawGraph(){
Object[] test = new Object[results.size()];
int index = 0;
for (Entry<String, TupleList> mapEntry : results.entrySet()) {
test[index] = mapEntry.getValue();
index++;
}
BarChart chart = new BarChart();
chart.setSampleCount(4);
String[] values = new String[test.length];
for(int i = 0; i < test.length; i++)
{
values[i] = (String) test[i];
}
// double[] values = new double[] {32,32,65,65};
String[] sampleLabels = new String[] {"deny\nstatus", "TCP\nrequest", "UPD\nrequest", "ICMP\nrequest"};
String[] barLabels = new String[] {"STATUS", "TCP", "UDP", "PING"};
//chart.setSampleValues(0, values);
chart.setSampleColor(0, new Color(0xFFA000));
chart.setRange(0, 88);
chart.setFont("rangeLabelFont", new Font("Arial", Font.BOLD, 13));
错误 - -
java.lang.ClassCastException: somePackagename.datamodel.TupleList cannot be cast to java.lang.String
at com.ibm.biginsights.ExampleAPI.drawGraph(ExampleAPI.java:177)
at com.ibm.biginsights.ExampleAPI.main(ExampleAPI.java:95)
我异常@
String[] values = new String[test.length];
for(int i = 0; i < test.length; i++)
{
values[i] = (String) test[i];
谢谢
我假设错误发生在这里: values[i] = (String) test[i];
。 问题是您正在尝试将TupleList
类型的对象抛出到字符串中。 你需要做的是调用.toString()
方法,它应该给你一个对象的字符串表示。
但是请注意,您必须覆盖TupleList
类中的toString()
方法,以便您可以获得适合您需要的对象的字符串表示。
所以简而言之,只是做test[i].toString()
很可能会产生这样的东西: TupleList@122545
。 你需要做的是:
public class TupleList
...
@Override
public String toString()
{
return "...";
}
...
显然,您的测试数组包含元组列表。 你添加它们
Object[] test = new Object[results.size()];
int index = 0;
for (Entry<String, TupleList> mapEntry : results.entrySet()) {
test[index] = mapEntry.getValue();
index++;
}
然后你将TupleList转换为String ang get ClassCastException你可以使用toString。
values[i] = test[i].toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.