简体   繁体   English

Java Collection <Generic Type> 没有收藏品的排序

[英]Java Collection<Generic Type> Sorting without Collections

I'm really stuck on an assignment for school. 我真的被困在学校的任务上。 We are learning about Generic Types, and maybe this is me not just understanding them fully, but as part of one of the first methods we have to implement: 我们正在学习通用类型,也许这不仅是我完全理解它们,而是作为我们必须实现的第一个方法之一的一部分:

We have: 我们有:

public static <T> T min(Collection<T> c, Comparator<T> comp) {
        return null
}

And the requirements: 和要求:

Selects the minimum value from the Collection c , as defined by the supplied Comparator comp . 选择Collection c的最小值,由提供的Comparator comp定义。 This method throws an IllegalArgumentException if either c or comp is null, and it throws a NoSuchElementException if c is empty. 如果c或comp为null,则此方法抛出IllegalArgumentException如果c为空,则抛出NoSuchElementException The Collection c is not changed by this method. 此方法不会更改Collection c。

So I've gotten to here: 所以我到了这里:

public static <T> T min(Collection<T> c, Comparator<T> comp)
            throws IllegalArgumentException, NoSuchElementException {
        if (c != null && comp != null) {
            if (!c.isEmpty()) {

            } else {
                throw new NoSuchElementException();
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

We have to sort using a comparator, but CANNOT use the Collections class. 我们必须使用比较器排序,但不能使用Collections类。 I really just need some direction to start, I'm not asking you to do the assignment for me! 我真的需要一些指导才能开始,我不是要求你为我做任务!

It should be easy. 应该很容易。 Comparator is used to compare two elements not for sorting. 比较器用于比较两个不用于排序的元素。 Sorting is not necessary here. 这里不需要排序。 You don't want to change the collection, just find the minimum value. 您不想更改集合,只需找到最小值。 You can just take first one and iterate over the collection comparing choosen element to others, switching choosen element to another when it's bigger. 您可以先取一个并迭代集合,将选择元素与其他元素进行比较,将选择元素切换为另一个元素。 This is the way to find the minimum. 这是找到最小值的方法。

Pseudocode of what you need to add to your example: 您需要添加到示例中的伪代码:

  • Save the first element in a variable call "minimum". 将第一个元素保存在变量调用“minimum”中。 As it is declared generic the type of the object is T. 因为它被声明为泛型,所以对象的类型是T.
  • Iterate the collection (Clue: every collection has an iterator) 迭代集合(线索:每个集合都有一个迭代器)
  • Compare each element with the "minimum" found. 将每个元素与找到的“最小值”进行比较。 If lower than assign it to the minimum. 如果低于将其指定为最小值。
  • Return the variable minimum. 返回最小变量。

I won't put the code as it is homework and you need to familiarize with the syntax. 我不会把代码放在家庭作业中,你需要熟悉语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM