java - 清晰地了解方法和 ArrayList

标签 java collections arraylist

我想了解如何创建方法的 ArrayList。

public class a {
public static b (){}
public static c (){}
public static d (){}
public static e (){}

public static void main(String[] arg){
ArrayList<Method> lst = new ArrayList<Method>();
lst.add(1, a());
lst.add(2, b());
lst.add(3, c());
lst.add(4, d());
lst.add(5, e());
}

我想知道为什么会这样,有人能解释一下吗:

public static Collection<? extends Method> a(){}
...
lst.addAll(1, a());

为什么要使用集合? 为什么不简单地使用 add(Object) 呢?

哦,还有一件事。如何执行 ArrayList 后面的方法?

for (Method i : lst){
i;}

感谢您的热心帮助。

最佳答案

如果您想使用反射,则应该使用 getDeclaredMethod 来获取该方法,正如这里的许多其他答案所指出的那样。然而,为了避免使用反射,Java 代码中更常见(也许更简洁)的做法是创建一个可以提供以下实现的接口(interface):

private static interface Foo {
  public void doFoo();
}

public static Foo a = new Foo() {
  public void doFoo() {
    // Do 'a' stuff here.
  }
}

public static Foo b = new Foo() {
  public void doFoo() {
    // Do 'b' stuff here.
  }
}

...

public static Foo e = new Foo() {
  public void doFoo() {
    // Do 'e' stuff here.
  }
}

public static void main(String[] arg){
  ArrayList<Foo> lst = new ArrayList<Foo>();
  lst.add(1, a);
  lst.add(2, b);
  lst.add(3, c);
  lst.add(4, d);
  lst.add(5, e);
}

然后,要调用该函数,您可以对列表中的每个 Foo 对象调用 doFoo()

关于java - 清晰地了解方法和 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21394041/

相关文章:

java - 交换数组列表的内容

scala - 更改 scala mutable.HashMap 的默认容量/负载因子

java - 以表格格式在jsp中显示来自servlet的arraylist值

java - 使用正则表达式检查特定字符串

java - java服务器和android客户端之间的SSL连接失败

java - 将包/类名称列表转换为父/子数据结构

Java:在数组列表中删除期间出现运行时错误

java - Arraylist - 使用现有索引的添加 - 添加新值和旧值

java - 如何为未配置 web.xml 的 Web 应用程序指定显示名称

java - 如何动态更改 JXTreeTable 中特定单元格的颜色