Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom method for ArrayList

Tags:

java

arraylist

Hello I would like to make a custom method for ArrayList class.

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();

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));

To sum it up:

    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)));

Will print: "asd" "asd".

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.

like image 718
IdontwearString Avatar asked Dec 17 '25 21:12

IdontwearString


2 Answers

Custom method >>

public class MyArrayList<E> extends ArrayList<E> {

    public E getLastItem(){
        return get(size()-1);
    }

}

How to use it >>

MyArrayList<String> list= new MyArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.getLastItem());
like image 154
Kerwin Avatar answered Dec 20 '25 10:12

Kerwin


what you need requires to extend the ArrayList classs, but you should consider using instead a

Map<String, Object>

with that approach you can do something like

myMap.get("myObject1");
like image 29
ΦXocę 웃 Пepeúpa ツ Avatar answered Dec 20 '25 10:12

ΦXocę 웃 Пepeúpa ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!