简体   繁体   English

在方法中实现 generics 的最佳方法是什么?

[英]Best way to implement generics in methods?

I'm having issues with a programming exercise because the book I'm reading only showed how to use print generic methods.我在编程练习时遇到问题,因为我正在阅读的书只展示了如何使用 print 泛型方法。 Which is easy.这很容易。 But the exercise asks to find the the largest and smallest value of an ArrayList.但该练习要求找到 ArrayList 的最大值和最小值。 I figured out a way to do it, shown in my code, but I'm just thinking to myself what's the point of using generics in the first place?我想出了一种方法,在我的代码中显示,但我只是在想,首先使用 generics 有什么意义?

Here are the exercise instructions:以下是练习说明:

Write a generic class named MyList, with a type parameter T. The type parameter T should be constrained to an upper bound: the Number class.使用类型参数 T 编写一个名为 MyList 的通用 class。类型参数 T 应限制为上限:数字 class。 The class should have as a field an ArrayList of T. Write a public method named add, which accepts a parameter of type T. When an argument is passed to the method, it is added to the ArrayList. class 应该有一个 T 的 ArrayList 作为字段。编写一个名为 add 的公共方法,它接受 T 类型的参数。当参数传递给该方法时,它被添加到 ArrayList。 Write two other methods, largest and smallest, which return the largest and smallest values in the ArrayList.编写另外两个方法,最大和最小,它们返回 ArrayList 中的最大值和最小值。

My code:我的代码:

//Main

import java.io.*;
import java.util.*; 

public class Main {

    static PrintWriter writer = new PrintWriter(System.out, true);

    public static void main(String[] args) throws IOException {

        ArrayList<Integer> list = new ArrayList<>();

        MyList<Integer> myList = new MyList<>(list);

        myList.add(3);
        myList.add(5);
        myList.add(44);
        myList.add(654);

        int first = myList.getArrayList().get(0);
        int largest = 0;
        int smallest = 0;

        for (int i = 1; i < list.size(); i++) {
            largest = myList.getLargest(first, myList.getArrayList().get(i));
            smallest = myList.getSmallest(first, myList.getArrayList().get(i));
        }

        System.out.println("Largest: " + largest + "\nSmallest: " + smallest);

    }
}

//MyList Class

import java.util.ArrayList;

public class MyList <T extends Number> {
    private ArrayList<T> arrayList;

    public MyList(ArrayList<T> arrayList) {
        this.arrayList = arrayList;
    }

    public void add(T item) {
        arrayList.add(item);
    }

    public ArrayList<T> getArrayList() {
        return arrayList;
    }

    public int getLargest(int x, int y) {
        return Math.max(x, y);
    }

    public int getSmallest(int x, int y) {
        return Math.min(x, y);
    }
}

If I try writing the methods with T types I get errors when using operators like > or + and Math.max() also won't work.如果我尝试使用 T 类型编写方法,则在使用 > 或 + 等运算符时会出现错误,并且 Math.max() 也不起作用。 I understand why now, I just don't understand what type am I suppose to return and input for the methods.我现在明白为什么了,我只是不明白我应该为方法返回和输入什么类型。 int, Integer, or T?整数,Integer,还是 T? And if I wanted to use a an ArrayList using doubles what then so the methods can work with both types?如果我想使用 ArrayList 使用双打,那么这些方法可以同时使用这两种类型吗? Any input as to what would be the best way to solve this problem using generics would be greatly appreciated.任何有关使用 generics 解决此问题的最佳方法的输入将不胜感激。 Thank you.谢谢你。

I won't do your homework for you, but I can put you on the right track...我不会为你做作业,但我可以让你走上正轨……

1 - I would define my ArrayList and initialized it on the same line (and not require the user to supply one on the constructor). 1 - 我会定义我的 ArrayList 并在同一行初始化它(并且不需要用户在构造函数上提供一个)。

public class MyList<T extends Number> {
  private ArrayList<T> arrayList = new ArrayList<T>();

2 - Define your two methods to return T 2 - 定义你的两种方法来返回 T

public T getLargest() {
}

public T getSmallest() {
}

3 - You'll want to convert everything to Double's (the largest possible Number implementation) 3 - 您需要将所有内容都转换为 Double(最大可能的 Number 实现)

T largest = (T) Double.valueOf(0f);

T smallest = (T) Double.valueOf(Double.MAX_VALUE);

4 - Loop through all the numbers in your arrayList property and do the appropriate comparisons 4 - 遍历 arrayList 属性中的所有数字并进行适当的比较

for (T number : numbers) {
  // because T is an extension of Number, we can invoke the doubleValue method
  // offered on the Number class
  // convert your T variables to doubles
  double v = number.doubleValue();

  // you can then compare the doubleValue to keep the largest/smallest values.
}

Hope this was helpful without doing your homework for you.希望这对您有所帮助,而无需为您做功课。 :-) :-)

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

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