【问题标题】:How we can call the methods with the help of an array object?我们如何在数组对象的帮助下调用方法?
【发布时间】:2017-12-16 18:05:34
【问题描述】:

我们如何在数组对象的帮助下调用方法?

例如:

class Employee
    {
        int value;

        Employee(int value)
        {
            this.value = value;
        }

        public void checkValue(int value1, int value2)
        {
            // i want to check here value1 & value2 is there or not in array
            // Or in another word I want to retrieve every element of the array in this method.   
        }
    }

    public class Test
    {
        public static void main(String arg[])
        {
            Employee e1[] = { new Employee(100), new Employee(200), new Employee(300) };

            e1.checkValue(100, 200);

        }
    }

所以在调用 e1.checkValue(100, 200) 时出现编译时错误,我只想以这种方式调用。这个问题是在一次采访中问我的。

【问题讨论】:

  • 你不能。该方法是在哪里定义的,您期待什么?
  • 是否要循环遍历数组并在其中的每个元素上调用方法?
  • someMethod 是什么?或者换句话说 - 你想要实现什么
  • 在该方法中,我想读取调用任何特定方法的数组对象的每个元素。方法可以是任何方法,就像我给出的例子一样 e1.someMethod();
  • 来吧,你可以而且应该改进这个问题,因为它非常不完整且难以回答。这就像我们不得不点点滴滴地从你身上拖出信息,而没有人喜欢玩那个游戏。请展示更多真实代码并详细说明问题。

标签: java arrays


【解决方案1】:

Arrays.stream(your array) 将提供一个流。 在流中使用您的输入应用过滤器方法 然后使用收集器收集结果。

这应该是 Java 8 的首选。

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    相关资源
    最近更新 更多