2011-04-13 103 views
0

我不是肯定就如何解釋這一點,但基本上我想指的是列表這是元素A的(可從任何列表)。但是會發生的是,當它通過列表的元素時,它將比較兩個不同的列表,並最終不匹配。即將包含前面b的原始列表與包含元素A的列表進行比較。現在我只是想知道如何將元素A的前面設置爲b,以便我可以比較它的位置。Java:如何引用類中的一個類,但引用另一個元素?

/*front is a dummy element used to keep position. 
List is a class i have made under requirements of naming for subject. 
i don't want a solution. I only want to know about how to do it. 

This is what is an example code of whats causing the problem USED IN DRIVER PROGRAM 
DLL.concat(DLL2); 
it is basically getting DLL's front and going through the loop when it should be using DLL2's. 

DLL and DLL2 are both Lists 
***/ 


    //will return the index of the Element for comparing 

    private int checkElement(Element A){ 

     Element b = front; 

      int i = 0; 
      while (b != a && i<size) 
      { 
       b = b.next; 
       i++; 
      } 

      return i; 
     } 


//edit: add 

//size is the size of the list gets increased everytime a variable is added to the list on top of the dummy element. 

//Item is a private class inside the List class. it contains the values: element,next, previous in which element contains an object, next and previous contain the next element in the list and the previous one (its a double linked list) 

// this is what causes the error to turn up in the above method as im using two different lists and joining them. 

    public void concat(List L){ 
     if (splice(L.first(),L.last(),last())){ 
      size = size+L.size; 
     } 
    } 

//this is the splice method for cutting out elements and attaching them after t 
//just using the check method to assert that a<b and will later use it to assert t not inbetween a and b 

public boolean splice(Element a, Element b, Element t){ 

     if (checkElement(a) < checkElement(b)){ 

      Element A = a.previous; 
      Element B = b.next; 
      A.next = B; 
      B.previous = A; 

      Element T = t.next; 

      b.next = T; 
      a.previous = t; 
      t.next = a; 
      T.previous = b; 
     return true; 
     } 
     else { 

     System.out.println("Splicing did not occur due to b<a");   
     return false; 
     } 

    } 
+0

對不起,我認爲語言障礙正在使一個複雜的問題變得更加複雜。你能向我們展示更多的代碼嗎?例如,「尺寸」是什麼,「前」是什麼?該代碼是否是列表結構的內部? – 2011-04-13 01:13:17

回答

1

因此,儘管我的評論,我看到一個明顯的問題。您不能在引用類型上使用相等運算符。也就是說,除了原始類型(double,int等)之外的任何東西。會發生什麼事情是比較實例的地址,除非它們實際上是相同的對象(內存中的地址相同),否則它不會返回true。也許這就是你想要的,但我懷疑不是。您需要覆蓋的方法

public boolean equals(Object obj); 

,並用它來比較給定類的兩個實例。我的假設是否正確?

編輯好吧,我想我的原始猜測是正確的。它起作用,如果它們來自同一個列表,因爲它們最終是相同的元素(存儲在同一個內存位置)。您需要使用equals()!equals()而不是==!=。嘗試一下,看看它是否能解決你的問題。另外,不要只用它們,你必須重寫equals來實際比較元素的內部屬性。

+0

它確實工作,當我使用列表中的元素。然而,如果我使用另一個列表中的元素,它仍然指的是原來的列表...生病發布多一點的代碼 – Stef 2011-04-13 01:51:23

+0

在上面的編輯如果我使用的方法,只是在一個列表上使用splice方法,它作爲在checkelement方法中創建的元素b來自同一個List。這就是爲什麼我需要知道是否像使用** this **的方式來引用項目a的前端(這是一個虛擬值),因此將能夠得到它的工作。 – Stef 2011-04-13 02:08:27

+0

@Stef看我上面的編輯 – 2011-04-13 02:26:30

相關問題