Well, the array is declared as
PQHeap[] pq;
So it doesn't contain Element
instances, but PQHeap
instances. So pq[i]
is of type PQHeap
, and PQHeap
doesn't have a key
field, hence the compilation error.
Question
Suppose I have an array A of elements E that each contain an integer key and some object data. I want extract the key for the i's element of the array A, and compare to some value like
A[i].key>somevalue
The problem is I don't know the correct operation to perform this comparison. In my program, I can access the key of an element by typing
E.key
An since the i's element of A seems to be an element E I would think the first snippet would work, however it does not.
The elements are declared as
public class Element {
public int key;
public Object data;
public Element(int i, Object o){
this.key = i;
this.data = o;
}
}
Constructor for the array public class PQHeap implements PQ { //constructor private PQHeap[] pq;
public PQHeap(int maxElms){
pq = new PQHeap[maxElms];
}
...
Some method
private void IncreaseKey(Element e){
if (e.key < pq[i].key){
System.out.println("new key is larger than current key");
}
For example, the line with the if statement, the error is "key cannot be resolved or is not a field" Operations like pq.length work fine, and e.key in itself also works
La solution
Well, the array is declared as
PQHeap[] pq;
So it doesn't contain Element
instances, but PQHeap
instances. So pq[i]
is of type PQHeap
, and PQHeap
doesn't have a key
field, hence the compilation error.