【发布时间】:2012-09-07 17:19:04
【问题描述】:
我有一系列 String[] 数组,它们是单词列表。类似的东西:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
现在我想为每个列表创建一个函数,给定一个数字,返回相应的元素(单词):
public String GetFromListOne(int key) { return ListOne[key];}
有没有办法避免手动编写每个 getter 函数?
例如,在 PHP 中,我会使用魔术方法 __call,
或作为带有列表名称的参数传递并动态引用它。
有没有办法在 Java 中做类似的事情?
或者是实现相同结果的替代策略?
【问题讨论】:
-
为什么你的代码不能只做
ListXXX[idx]?更简单。更小。更快。 -
为什么不使用列表[list_id][element_id]?
-
@jmendeth OP 正在寻求一种方法来避免创建
getListOneItem、getListTwoItem、getListThreeItem等等...... -
此外,我认为您没有表达正确的概念。你不是说有一个
Entry对象列表,每个对象都有一个one、two和three属性吗? -
@LuiggiMendoza 我在问 OP 为什么他需要这些功能 :) 他的代码可以直接执行
ListOne[index]或Lists[1][index]而不是GetFromListOne(index)。更简单。更小。 ...是的,你已经知道了。
标签: java arrays object inheritance