如果我的方法是从任何类型接受队列,如何确定方法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();
}
}
}
答案 0 :(得分:0)
如果要确定对象的类型:
if (l1 instanceof LinkedList) {
//Do something
}
同样的解决方案也适用于其他对象。