문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top