java - 当项目排队到队列对象上时,队列对象保持为空

标签 java generics inheritance linked-list queue

我有两个类(class),ClubpartyClub extends通用Queue<E>并实现 fitnessInterface

Queue<E> implements QueueInterface<E>

俱乐部

public class Club extends Queue<Bachelor> implements fitnessInterface{

   protected Queue<Bachelor> bachelorQ;

   public Club(){
       super();

       bachelorQ = new Queue<Bachelor>();
    }

public boolean Eligible(Bachelor bachelor){

       if(bachelor==null){throw new NullPointerException();}

       return true;
     }

@Override
public QueueInterface<Bachelor> enqueue(Bachelor bachelor){

       if(bachelor==null){
             throw new NullPointerException();
       else{
             bachelorQ.enqueue(bachelor); }

       return this; //the class queue
    }
}

聚会

public class Party extends Club{
       super();
    }

@Override
public boolean Eligible(Bachelor bachelor){

   if(bachelor==null){throw new NullPointerException();}

   if(bachelor.getPushups()>=25){return true;}

   return false;

   }
}

Bachelor类扩展了 QueueInterface并有一个接受 Integer 的构造函数作为参数,除其他外,还有 getPushUps()方法。

问题是当我创建 Party 时反对并尝试将单例汉拉尔夫或查理排入队列,它仍然是空的。

我的通用队列类工作完美。它有dequeue , enqueue , isEmpty , peek , sizetoString方法。一切工作正常。

主要

public static void main(String[] args){

     Party bigParty = new Party();

     Bachelor jack,charlie,ralph;

     jack = new Bachelor(15);
     ralph = new Bachelor(27);
     charlie = new Bachelor(39);

     //Eligibility tests
     System.out.println(bigParty.Eligible(charlie));
     System.out.println(bigParty.Eligible(ralph));
     System.out.println(bigParty.Eligible(jack));

     System.out.println(bigParty.enqueue(ralph));
     System.out.println(bigParty.enqueue(charlie));
     System.out.println(bigParty.size());
     System.out.println(bigParty.bachelorQ.size());
}

输出

true
true
false
[]
[]
0
2
<小时/>

最佳答案

这就是当您混合继承和组合时会发生的情况。检查这个方法:

@Override
public QueueInterface<Bachelor> enqueue(Bachelor bachelor){

       if(bachelor==null){
             throw new NullPointerException();

       bachelorQ.enqueue(bachelor); 

       return this; //the class queue
    }
}

您正在调用enqueue()bachelorQ ,但返回this 。两者都是不同的引用,指向不同的对象。

您应该返回bachelorQ ,或者只是调用 super.enqueue(bachelor) .

顺便说一句,因为您已经扩展了 Queue<Bachelor> ,我认为没有必要 bachelorQ那里有引用。您只需将其删除即可。或者甚至更好,只是不要从 Queue<Bachelor> 延伸。只要有可能,您应该更喜欢组合而不是继承。

关于java - 当项目排队到队列对象上时,队列对象保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22343723/

相关文章:

java - 不使用 StringBuffer.reverse() 反转字符串

java - 在 Google App Engine 上使用 HttpsURLConnection 检索证书详细信息

Java 泛型转换

c++ - 无法在派生类的构造函数的初始化中访问 protected 函数

c++ - 通过指向其非模板父类的指针将模板值分配给类模板

Java对象引用问题

java - Weblogic 12c 服务器是否忽略 http.proxy* 参数?

java - 类型转换比较器为子类工作

Java - 在编译时不知道结果类型的情况下,方法如何返回变量类型对象?

C++ 多继承顺序和虚函数