1

我有一个带有字符串和 tupleList 的地图。我正在尝试将 tupleList 转换为双数组,但我遇到了类型转换异常。我的代码是——

Map<String, TupleList> results = null; -- Some data in it and TupleList has int or double value.

公共无效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];

谢谢

4

2 回答 2

2

我假设错误发生在这里:values[i] = (String) test[i];. 问题是您试图将类型的对象TupleList放入字符串中。您需要做的是调用该.toString()方法,该方法应该为您提供对象的字符串表示形式。

但是请注意,您必须toString()在类中覆盖该方法,TupleList以便您可以获得适合您需要的对象的字符串表示形式。

所以简而言之,只是做test[i].toString()很可能会产生类似这样的东西:TupleList@122545. 你需要做的是:

public class TupleList
...

@Override
public String toString()
{
    return "...";
}

...
于 2012-08-10T05:51:55.527 回答
1

显然,您的测试数组包含 TupleLists。您将它们添加到

    Object[] test = new Object[results.size()];
    int index = 0;
    for (Entry<String, TupleList> mapEntry : results.entrySet()) {
        test[index] = mapEntry.getValue();
        index++;
    }

然后将 TupleList 转换为 String 并获取 ClassCastException 如果需要,可以使用 toString。

values[i] = test[i].toString();
于 2012-08-10T05:51:04.673 回答