泛型在一个ArrayList对象比较 [英] Generics comparing objects in an ArrayList

查看:125
本文介绍了泛型在一个ArrayList对象比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建在一个数组列表进行比较的对象,并返回最大的泛型类。我的问题是,我不能肯定我完全理解泛型是如何工作的。

I'm trying to create a generic class that compares objects in an array list and returns the largest. My issue is that I'm not quite sure I understand completely how generics work.

衡量的:

import java.util.ArrayList;

/**
   Describes any class whose objects can be measured.
*/

public abstract class Measurable<T>{

abstract double getMeasure();

    public static <T extends Measurable<T>> T getLargest(ArrayList<T> objects){
        T largest = objects.get(0);
        for(int i = 0; i < objects.size(); i ++){
            if(largest.getMeasure() == objects.get(i).getMeasure()){
                largest = objects.get(i);
            }
        }
        return largest;     
    }

}

盒:

import java.awt.Rectangle;
import java.util.ArrayList;


public class Box extends Measurable {

    private Rectangle box;
    private static ArrayList<Rectangle> rectangles;

    public Box(){
        box = new Rectangle();
        rectangles = new ArrayList<Rectangle>();
    }

    public ArrayList<Rectangle> create(){
        for(int i = 0; i < 10; i++){
            box = new Rectangle((int) Math.random(), (int) Math.random());
            rectangles.add(box);
        }
        return rectangles;
    }

    @Override
    public double getMeasure() {
        double area = 0;
        for(int i = 0; i < rectangles.size(); i++){
            area = rectangles.get(i).getWidth()*rectangles.get(i).getHeight();
        }
        return area;
    }

    public static void main(String[] args){
        Box b = new Box();
        b.getLargest(b.create());
    }
}

我对面,它说一个问题来了的方法getLargest(ArrayList中)在类型测不适用于参数(ArrayList的),但我不应该能够使用任何对象为getLargest类?

I'm coming across an issue where it says "The method getLargest(ArrayList) in the type Measurable is not applicable for the arguments (ArrayList)" but shouldn't I be able to use any object for the getLargest class?

推荐答案

当你写的, getLargest 预计该对象的传递给它的的在列表实施可测量,但 java.awt.Rectangle中的没有。

As you wrote it, getLargest expects the objects passed to it in the List to implement Measurable, but java.awt.Rectangle does not.

当你写

public static <T extends Measurable<T>> T getLargest(ArrayList<T> objects){

这是声明了一个 T 不同的的,但名称相同,因为 T 可测量类作为一个整体,这很可能导致总的混乱。

that declares a T that is different, but named the same, as the T in the Measurable class as a whole, which is likely to lead to total confusion.

如果你真的在你的code替换 T 长方形,你可以看到你试图调用 Rectangle.getMeasure(),这是一个不存在的方法。

If you actually replace T with Rectangle in your code, you can see that you're trying to call Rectangle.getMeasure(), which is a method that does not exist.

这篇关于泛型在一个ArrayList对象比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆