0

I'm trying to run a program I have made in Java, but I don't know what is happening that it is giving me the following error:

Exception in thread "main" java.lang.ClassCastException: 
java.lang.String cannot be cast to java.util.ArrayList

Here is the code:

 public static ArrayList connections(ArrayList list3) {

        ArrayList connections = new ArrayList();
        int row1 = 1;
        int row2 = 0;
        int col = 0;

        connections.add(new ArrayList());
        ((ArrayList)connections.get(0)).add(0);
        ((ArrayList)connections.get(0)).add(1);

        System.out.print(((ArrayList)connections.get(0)).get(0));

        while(row1 < list3.size()) {


            if(((ArrayList)list3.get(row1)).get(col).equals(((ArrayList)connections.get(row2)).get(col))){
                connections.add(((ArrayList)list3.get(row1)).get(1));
                row1++;
            }

            else {
                connections.add(new ArrayList());
                connections.add(((ArrayList)list3.get(row1)).get(0));
                row2 = row1;
                row1++; 
            }
        }

        return connections;
     }

It seems that the error is in the if statement. Can somebody help me with this?

2
  • 1
    If you look at the stack trace of your exception, it should show you in which line the error is. This helps in finding the mistake. Commented Jul 27, 2011 at 19:21
  • 2
    Using generics will help you avoid these errors. Commented Jul 27, 2011 at 19:21

2 Answers 2

3
if(((ArrayList)list3.get(row1)).get(col).equals(((ArrayList)connections.get(row2)).get(col))){

should read

if(((ArrayList)list3.get(row1)).get(col).equals(( ((ArrayList)connections).get(row2)).get(col))){

You are casting connections.get(row2) instead of casting connections first and then doing a get on the arraylist.

EDIT -- You should definitely refactor the code to use Java 1.5 functionality aka generics. If that's not an option, you should refactor the code to be more readable -- for example : your method is called "connections" and then your variable is called "connections"

Sign up to request clarification or add additional context in comments.

Comments

2

You should also use generics instead of casting. That way you will get an error at compile-time if you do this and your code will be type-safe. Generics just specify the type you are using to the compiler so it can check the types at compile-time.

Example:

ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
list.add(new ArrayList<Integer>());

list.get(0).add(0);
list.get(0).add(1);
list.get(0).add(2);

More about generics here.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.