【发布时间】:2018-05-13 20:55:18
【问题描述】:
如果我的方法接受任何类型的队列,如何确定方法 arg 是 ArrayBlockedQueue() 还是 LinkedList() 队列?
我使用.equals 作为以下它总是返回true
Queue q1 = new LinkedList();
Queue q2 = new ArrayBlockingQueue(4);
System.out.println(l1.equals(q1));
然后我尝试了以下我遇到了非法参数异常
public static void add2Q (Queue q) {
if(q.equals( new ArrayBlockingQueue(q.size()))){
q.offer(2);
q.offer(5);
q.offer(9);
q.offer(0);
q.offer(-1);
} else {
// thorws exception with add if exceeded
try {
q.add(2);
q.add(5);
q.add(4);
q.add(9);
q.add(10);
} catch (IllegalStateException e){
System.out.println("you are using ArrayBlockQueue of size "+ q.size() );
//e.printStackTrace();
}
}
}
【问题讨论】:
-
为什么?你不应该在意。这就是传递
Queue对象而不是特定类型的全部意义。 -
@EJP 这只是为了检查将元素添加到队列时使用哪种方法