ArrayList的自定义方法 [英] Custom method for ArrayList

查看:112
本文介绍了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)并获得相同的结果.我希望你能理解我的问题.我知道这可能是一个愚蠢的解决方案,我只能使用Map.但这只是出于学习目的,我将一无所用.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆