【问题标题】:Java - How to check if the queue of type ArrayBlockedQueue of LinkedList [duplicate]Java-如何检查LinkedList的ArrayBlockedQueue类型的队列是否[重复]
【发布时间】: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 这只是为了检查将元素添加到队列时使用哪种方法

标签: java arraylist queue


【解决方案1】:

如果要判断对象的类型:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 2018-02-26
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2023-04-03
    • 2013-05-06
    相关资源
    最近更新 更多