目前我正在嘗試編寫一個程序來創建一個MinHeap,儘管我似乎無法讓ArrayList正常工作,因爲其中一個類似乎無法與另一個類連接。當一個類試圖將元素添加到ArrayList時,會出現問題。課程由----Java類和ArrayList
public interface QUEUE {
public Element getMin();
public void add(Element e);
}
public class Element {
public int key;
public Object data;
public Element(int i, Object o){
this.key = i;
this.data = o;
}
}
class TestProject {
public static void main(String[] args) {
System.out.println();
QUEUE q = new QUEUEHeap(10);
System.out.println(" 5, 1, 2, 33, -1, 3, 1, 2, 23, 13");
System.out.println();
q.insert(new Element(5,new Integer(5)));
q.insert(new Element(1,new Integer(1)));
q.insert(new Element(2,new Integer(2)));
}
import java.util.ArrayList;
public class QUEUEHeap implements QUEUE {
private ArrayList<Integer> q;
public PQHeap(int maxElements) {
q = new ArrayList<>(maxElements);
System.out.println("Element at index 1: " + q);
}
public Element getMin() {
}
public void insert(Element e) {
q.add(e.key,e.data); //e.key = i, e.data = o
}
}
新的錯誤分離:
no suitable method found for add(int,Obje
q.add(e.key,e.data); //e.key = i, e.data = o
^
method List.add(int,Integer) is not applicable
(argument mismatch; Object cannot be converted to Integer)
method AbstractList.add(int,Integer) is not applicable
(argument mismatch; Object cannot be converted to Integer)
method ArrayList.add(int,Integer) is not applicable
(argument mismatch; Object cannot be converted to Integer)
錯誤是來自插入方法的pq未定義。雖然我不知道如何解決這個問題。看來插入方法不能訪問創建的ArrayList?請幫忙。 – Colour 2015-04-03 17:25:41
@Prashant然後沒有這樣的方法!準確的意思是什麼?無論如何要讓它像那樣工作? – Colour 2015-04-03 17:29:56
@Prashant ['ArrayList#add(int,E)'](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-int-E-)exists 。這是將元素放在一個特定的索引 – 2015-04-03 17:33:42