【问题标题】:java: how to call a method on arraylist without knowing the type of objectjava:如何在不知道对象类型的情况下调用arraylist上的方法
【发布时间】:2017-12-04 22:27:08
【问题描述】:

我有一个 intersect 方法,它接受两个包含相同类型对象的 ArrayList,并返回两个列表中的对象列表。

public static ArrayList<TimeSlot> intersectTS(ArrayList<TimeSlot> List1, ArrayList<TimeSlot> List2)
{
    ArrayList<TimeSlot> intersection = new ArrayList<TimeSlot>();
    for(TimeSlot TS1 : List1)
    {
        for(TimeSlot TS2 : List2)
        {
            if(TimeSlot.Equals(TS2,TS1))
            {
                intersection.add(TS2);
            }
        }
    }
    return intersection;
}

现在它只能使用 TimeSlot 对象,我必须为要使用此方法的所有其他类型的对象创建一个几乎相同的方法。

有没有一种方法可以做到这一点?

谢谢

【问题讨论】:

  • 使用泛型? public static ArrayList&lt;T&gt; intersectTS(List&lt;T&gt; list1, List&lt;T&gt; list2)
  • 假设您的意思是equals,而不是TimeSlot 类中的一些特殊的Equals 方法,那么svasa 的评论就是正确答案。
  • 请遵守 Java 命名约定,看看TimeSlot.Equals 的代码会很有趣。为什么不是普通的equals 方法,或者它做了什么不同的事情?
  • @svasa 的回答在 ArrayList&lt;T&gt; 之前省略了 &lt;T&gt;,但在其他方面是正确的。
  • 是的,我猜 Equals 有点奇怪。我拿起 java 来做一个项目,但我对内部工作原理不太了解。我只擅长 Python。 “等于”是一种特殊的方法吗?

标签: java object arraylist


【解决方案1】:

方法 1 - Generics

public static <T extends TimeSlot> ArrayList<T> intersectTS(ArrayList<T> List1, ArrayList<T> List2)
{
    ArrayList<T> intersection = new ArrayList<T>();
    for(T TS1 : List1)
    {
        for(T TS2 : List2)
        {
            if(TimeSlot.Equals(TS2,TS1))
            {
                intersection.add(TS2);
            }
        }
    }
    return intersection;
}

现在假设您传入的通用对象具有Equals(T, T) 方法,并告诉编译器您将只传入满足该条件的对象,您可以使用&lt;T extend TimeSlot&gt; 其中TimeSlot 是一个接口。


方法 2 - Inheritance

public static ArrayList<ParentObject> intersectTS(ArrayList<ParentObject> List1, ArrayList<ParentObject> List2)
{
    ArrayList<ParentObject> intersection = new ArrayList<ParentObject>();
    for(ParentObject TS1 : List1)
    {
        for(ParentObject TS2 : List2)
        {
            if(ParentObject.Equals(TS2,TS1))
            {
                intersection.add(TS2);
            }
        }
    }
    return intersection;
}

这种方法假设您有一个对象ParentObject,它有一个方法Equals(ParentObject, ParentObject),并且您的TimeSlot 类扩展了ParentObject


如果您对任何一种方法都没有更多指导,请告诉我,我会详细解答。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多