tags:

views:

268

answers:

3

Can an ArrayList of Node contain a non-Node type?

Is there a very dirty method of doing this with type casting?

+5  A: 

Yes, but you will get class cast exceptions if you try to access a non-node element as if it were a node. Generics are discarded at (for) runtime.

For example:

import java.util.*;
import java.awt.Rectangle;

public class test {
    public static void main(String args[]) {
        List<Rectangle> list = new ArrayList<Rectangle>();
        /* Evil hack */
        List lst = (List)list;

        /* Works */
        lst.add("Test");

        /* Works, and prints "Test" */
        for(Object o: lst) {
            System.err.println(o);
        }

        /* Dies horribly due to implicitly casting "Test" to a Rectangle */
        for(Rectangle r: list) {
            System.err.println(r);
        }
    }
}
Draemon
+1  A: 

Given:

  List<Node> nodelist = new ArrayList<Node>();
  Object toAdd = new Object();

then:

  ((List) nodelist).add(toAdd);

or

  ((List<Object>) nodelist).add(toAdd);

will do the hack. Ick. I feel dirty. But, you should not do this. If you really need to mix types, then do this:

  List<Object> mixedList = new ArrayList<Object>(list);
  mixedList.add(toAdd);

That solution, at least, will indicate to others that they have to beware that any subclass of Object can be in the list.

Chris Dolan
A: 

Assuming you are using Generic to have an ArrayList, you can add non-Node into it by using reflection because during runtime the type information is not kept.

Depend on how you get the object out of the ArrayList, you might get hit by ClassCastException.

If you really have a need on non-specific type in your ArrayList, then why don't you just use it without Generic?

DJ