ArrayList 的自定义方法 [英] Custom method for ArrayList
问题描述
您好,我想为 ArrayList 类创建一个自定义方法.
Hello I would like to make a custom method for ArrayList class.
假设我创建了一个新的 ArrayList.
So lets say I make a new ArrayList.
ArrayList<String> list = new ArrayList<String>
我想做一个可以在列表中调用的方法.像这样:
I would like to make a method I can call on list. Something like this:
list.myMethod();
我想用我的方法解决的是,您可以通过对象名称获取对象,而不是在 ArrayList 中获取索引.
What I want to solve with my method is so you can get an Object by Object name and not index inside the ArrayList.
所以基本上我想制作一个返回以下内容的方法:
So basically I want to make a method returning following:
list.get(list.indexOf(str));
总结一下:
ArrayList<String> list= new ArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.get(0));
System.out.println(list.get(list.indexOf(str)));
将打印:asd"asd".
Will print: "asd" "asd".
所以不要写:list.get(list.indexOf(Object))
我希望能够编写 list.myMethod(Object)
并获得相同的结果.我希望你明白我的问题.我知道这可能是一个愚蠢的解决方案,我可以只使用地图.但这仅用于学习目的,我不会使用任何东西.
So instead of writing: list.get(list.indexOf(Object))
I would like to be a able to write list.myMethod(Object)
and get the same result. I hope you understand my question. I know this is probably a dumb solution and I could just use a Map. But this is for learning purpose only and nothing I will use.
推荐答案
自定义方法>>
public class MyArrayList<E> extends ArrayList<E> {
public E getLastItem(){
return get(size()-1);
}
}
如何使用>>
MyArrayList<String> list= new MyArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.getLastItem());
这篇关于ArrayList 的自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!