繁体   English   中英

Java-如何在通用类中调用我的类T的方法

[英]Java - How to call a method of my class T in a generic class

我的类ListFromFile<T>扩展了ArrayList<T>遇到问题。 在该类中,我想创建一个通过其id属性查找元素并将其返回的方法。

T可以是来自Student,Teacher等类的对象。所有这些类都有用于测试id的equals方法。

我的问题是我不能使用测试ListFromFile的id的equals方法。

这是我的代码:

public class ListFromFile<T> extends ArrayList<T> implements Serializable {
    public T getElement(int id) {
        for ( T o : this ) {
             if ( o.equals((int)id) ) {
                  return o;
             }
        }

        return null;
    }
}

即使我在equals方法中指定我使用的是一个int的ID, getElement()也找不到该元素...

经过一些搜索后,似乎我必须按学生,教师等来扩展T,但是如何扩展倍数类?

谢谢

您应该将接口或抽象类与getId()方法一起使用。 T绑定为接口或抽象类的子类型。 使用接口,可能看起来像这样。

public interface ObjectWithId {
    int getId();
}

public class Student implements ObjectWithId {
    // ...
}

public class Teacher implements ObjectWithId {
    // ...
}


public class ListFromFile<T extends ObjectWithId> extends ArrayList<T> {
    public T getElement(int id) {
        for ( T o : this ) {
            if ( o.getId() == id ) {
                return o;
            }
        }

        return null;
    }
}

这是示例应用程序,显示了如何解决此问题:

import java.io.Serializable;
import java.util.ArrayList;

public class test2 {
    // define basic interface for all objects
    interface ObjectWithID {
        public int getId();
    }

    public static class Teacher implements ObjectWithID {
        private final int id;

        public Teacher(final int id) {
            this.id = id;
        }

        @Override
        public int getId() {
            return this.id;
        }
    }

    public static class Student implements ObjectWithID {
        private final int id;

        public Student(final int id) {
            this.id = id;
        }

        @Override
        public int getId() {
            return this.id;
        }
    }

    // note T extends syntax
    public static class ListFromFile<T extends ObjectWithID> extends ArrayList<T> implements Serializable {
        public T getElement(final int id) {
            for (final T o : this)
                if (o.getId() == id)
                    return o;
            return null;
        }
    }

    public static void main(final String[] args) {
        final ListFromFile list = new ListFromFile<>();

        list.add(new Teacher(1));
        list.add(new Teacher(2));
        list.add(new Teacher(3));

        list.add(new Student(4));
        list.add(new Student(5));
        list.add(new Student(6));

        System.out.println(list.getElement(1)); // print teacher
        System.out.println(list.getElement(4)); // print student
    }
}

暂无
暂无

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

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