- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在掌握某些东西时遇到了一些问题 - 我可能会完全错误地处理这件事。
我正在尝试创建一个扩展 ArrayList 的类,但有几个方法可以增加功能(至少对于我正在开发的程序而言。)
其中一个方法是 findById(int id),它在每个 ArrayList 对象中搜索特定的 id 匹配项。到目前为止它的工作,但它不会让我做 for (Item i : this) { i.getId(); }
我不明白为什么?
完整代码:
public class CustomArrayList<Item> extends ArrayList<Item> {
// declare singleton instance
protected static CustomArrayList instance;
// private constructor
private CustomArrayList(){
// do nothing
}
// get instance of class - singleton
public static CustomArrayList getInstance(){
if (instance == null){
instance = new CustomArrayList();
}
return instance;
}
public Item findById(int id){
Item item = null;
for (Item i : this) {
if (i.getId() == id) {
// something
}
}
return item;
}
public void printList(){
String print = "";
for (Item i : this) {
print += i.toString() + "\n";
}
System.out.println(print);
}
}
最佳答案
改变
public class CustomArrayList<Item> extends ArrayList<Item> {
到
public class CustomArrayList extends ArrayList<Item> {
我怀疑Item
是要存储在列表中的类的名称。通过添加 <Item>
在 CustomArrayList
之后您正在引入一个类型参数,它会影响此类。
与 <Item>
参数,你的代码等于
public class CustomArrayList<T> extends ArrayList<T> {
// ...
for (T i : this) { i.getId(); }
// ...
}
这显然不会总是有效,因为 T
可以指任何类型。
关于java - 扩展 ArrayList 和创建新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6524711/
如果有人能为我分解它,让我能理解它,我会非常感激。我知道它用于通过 apply 方法创建新对象。 Function.prototype.new = function () { var args
新版本的HADOOP中有一个方法。http://hadoop.apache.org/docs/current/api/org/apache/hadoop/fs/FileSystem.html#conc
根据支持库变更日志和 Fragment 类文档 ( https://developer.android.com/reference/android/support/v4/app/Fragment.ht
根据支持库更改日志和 Fragment 类文档 (https://developer.android.com/reference/android/support/v4/app/Fragment.htm
执行Async BigJob() 的无限运行任务的正确方法是什么?并且可以根据要求停止 提示:我正在尝试学习 [一种] 新方法来更新我现有的策略。 我有一个简单的程序(测试程序),它有一个开始 和停止
我将解释我的想法:我使用 python 作为谷歌应用程序引擎 + js + css 主项目将存储在 src 文件夹下,如下所示:\src \app <--- 这里是 gae 的所有 python 应用
我是一名优秀的程序员,十分优秀!