2011-04-13 98 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

相关问题