Java - 如何检查LinkedList的ArrayBlockedQueue类型的队列

时间:2017-11-30 02:11:00

标签: java arraylist queue

如果我的方法是从任何类型接受队列,如何确定方法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();
        }   
    }   
}

1 个答案:

答案 0 :(得分:0)

如果要确定对象的类型:

if (l1 instanceof LinkedList) {
   //Do something
}

同样的解决方案也适用于其他对象。