简体   繁体   中英

java : Class cast exception

I have a map with strings and tupleList. i am trying to get the tupleList into double array , but i am getting type cast exception. my code is --

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

error----

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)

i am getting exception @

  String[] values = new String[test.length];
        for(int i = 0; i < test.length; i++)
        {
            values[i] = (String) test[i];

Thanks

I am assuming that the error is taking place here: values[i] = (String) test[i]; . The problem is that you are trying to throw an object of type TupleList into a string. What you need to do, is to call the .toString() method, that should give you a string representation of the object.

Note however, you will have to override the toString() method within the TupleList class so that you can get a string representation of the object which suits your needs.

So in short, just doing test[i].toString() will most likely yield something along the lines of this: TupleList@122545 . What you need to do is this:

public class TupleList
...

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

...

Obviously your test array contains TupleLists. You add them at

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

And then you cast TupleList to String ang get ClassCastException You could use toString if you want.

values[i] = test[i].toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM