java 当类型未知时,如何迭代 Iterable 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15295526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:08:14  来源:igfitidea点击:

How do I iterate over an Iterable object when the type is not known?

javaalgorithmiterable

提问by Mirrana

For a homework assignment, I need to implement my own PriorityQueue and PriorityQueueSort. I used generics to get it working without the sort function, but now I'm stuck here..

对于家庭作业,我需要实现自己的 PriorityQueue 和 PriorityQueueSort。我使用泛型让它在没有排序功能的情况下工作,但现在我被困在这里..

public static void PriorityQueueSort(Iterable<?> list, 
    PriorityQueue<?,?> pq) {
  if (!pq.isEmpty()) {
    throw new IllegalArgumentException("Non-Empty PriorityQueue");
  }

  for (Object obj : list) {

  }
}

I need to pass in a list and an empty PriorityQueue, so my best guess at how to do this is just above. How should I attack this so that I can iterate through the list with unknown type, and add each element in that list with the proper type into the priority queue?

我需要传入一个列表和一个空的 PriorityQueue,所以我对如何做到这一点的最佳猜测就在上面。我应该如何解决这个问题,以便我可以遍历未知类型的列表,并将该列表中具有正确类型的每个元素添加到优先级队列中?



Edit:

编辑:

Here are a few more details since it was determined that I didn't include enough information.

由于确定我没有包含足够的信息,因此这里有更多详细信息。

I have a custom PriorityQueue class, and a custom Entry class that holds a key of type K, and a value of type V.

我有一个自定义的 PriorityQueue 类和一个自定义的 Entry 类,其中包含一个 K 类型的键和一个 V 类型的值。

I need to be able to take any iterable list with any type T and iterate through it, taking each item and add it to an initially empty PriorityQueue as a key with null value. I then need to continuously call removeMin() on my PriorityQueue and add it in order back into the same list object.

我需要能够获取任何类型 T 的任何可迭代列表并遍历它,获取每个项目并将其添加到最初为空的 PriorityQueue 作为具有空值的键。然后我需要在我的 PriorityQueue 上连续调用 removeMin() 并将它按顺序添加回同一个列表对象。

public class PriorityQueue<K extends Comparable<? super K>,V> {

  private Entry<K,V> _head;
  private Entry<K,V> _tail;
  private int _size;

  public PriorityQueue() {
    this._head = null;
    this._tail = null;
    this._size = 0;
  }

  public int size() {
    return _size;
  }

  public boolean isEmpty() {
    return (size() == 0);
  }

  public Entry<K,V> min() {
    if (_head == null) {
      return null;
    }
    Entry<K,V> current = _head;
    Entry<K,V> min = _head;;

    while (current != null) {
      if (current.compareTo(min) < 0) {
        min = current;
      }
      current = current.getNext();
    }
    return min;
  }

  public Entry<K,V> insert(K k, V x) {
    Entry<K,V> temp = new Entry<K,V>(k,x);
    if (_tail == null) {
      _tail = temp;
      _head = temp;
    }
    else {
      _tail.setNext(temp);
      temp.setPrev(_tail);
      _tail = temp;
    }
    return temp;
  }

  public Entry<K,V> removeMin() {
    Entry<K,V> smallest = min();
    smallest.getPrev().setNext(smallest.getNext());
    smallest.getNext().setPrev(smallest.getPrev());

    return smallest;
  }

  public String toString() {
    return null;
  }

  public static <K> void PriorityQueueSort(Iterable<? extends K> list,
        PriorityQueue<? super K, ?> queue) {

      for (K item : list) {
          queue.insert(item, null);
      }

      list.clear();
  }

  public static void main(String[] args) {
    PriorityQueue<Integer, Integer> pq = 
        new PriorityQueue<Integer, Integer>();

    pq.insert(4, 2);
    pq.insert(5, 1);


    System.out.println(pq.min().toString());
  }
}

回答by Jon Skeet

What you've got at the moment doesn't make sense in terms of the method signature - it would let you pass in a List<Button>and a PriorityQueue<String>for example.

就方法签名而言,您目前拥有的内容没有意义 - 例如,它会让您传入 aList<Button>和 a PriorityQueue<String>

I suspect you actually want something like:

我怀疑你真的想要这样的东西:

public static <T> void prioritySortQueue(Iterable<? extends T> iterable,
    PriorityQueue<? super T> queue) {

    for (T item : iterable) {
        queue.add(item);
    }
}

Note that the variance here just gives more flexibility - you could have a List<Circle>but a PriorityQueue<Shape>for example, and it's still type-safe.

请注意,这里的差异只是提供了更多的灵活性 -例如,您可以使用 a List<Circle>but a PriorityQueue<Shape>,它仍然是类型安全的。

EDIT: Now that we have more details, I think you want something like this:

编辑:现在我们有更多的细节,我想你想要这样的东西:

public static <K> void prioritySortQueue(Iterable<? extends K> iterable,
    PriorityQueue<? super K, ?> queue) {

    for (T item : iterable) {
        queue.put(item, null);
    }
}

(Assuming you have a putmethod. We still don't know what your PriorityQueueclass looks like.)

(假设你有一个put方法。我们仍然不知道你的PriorityQueue类是什么样的。)

回答by SLaks

You need to make the method generic so that you can refer to the type:

您需要使方法通用,以便您可以引用类型:

public static <T> void PriorityQueueSort(Iterable<T> list, 
PriorityQueue<?,T> pq) {