0

I have a problem in Java when using a for-each construct on an ArrayList. In one class, named Graph, I have the protected attribute

protected ArrayList<Edge<E>> edges

In my Edge class, I have the protected attribute

protected LinkedList<Connector<E>> pointers;

What I'm trying to do, in my Edge class, is to define a method to print on screen each pointer of each Edge of my Graph g. I tried using different approaches getting errors everytime, and then I ended up using the for-each loop (I thought it was the best choice since I know the type of the elements in the collection I'm trying to iterate on). My code is as follows:

public void printConnectors(Graph g){
    for (Edge<E> e: g.edges){
    System.out.println(e.iterator()); //I do have an iterator in my Edge class
    }
}

This is not working though, Eclipse gives me the following error:

Type mismatch: Cannot convert from element type Object to Edge

I know this may be a stupid error derived from something I'm not seeing in my code, but I can't get it to work. Can anyone help me and explain why the compiler tries to convert from Object to Edge even though edges should be an ArrayList of Edges?

Luca Giorgi
  • 910
  • 3
  • 14
  • 28

1 Answers1

4

You're using raw types. The code should be:

public void printConnectors(Graph<E> g) { // use the generic type Graph<E> here,
                                          // not the raw type Graph
    for (Edge<E> e: g.edges) {
        System.out.println(e.iterator()); 
    }
}

What is a raw type and why shouldn't we use it?

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • ...and for those of you wondering why this fixes it, raw types strip off all generic info, effectively (but not exactly) treating the instance and all its fields/methods as if their type was `Object` – Bohemian May 31 '14 at 15:54