IdontwearString
IdontwearString

Reputation: 367

Custom method for 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.

Upvotes: 3

Views: 2687

Answers (3)

Kerwin
Kerwin

Reputation: 1212

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

Upvotes: 4

freedev
freedev

Reputation: 30177

You should just extend the ArrayList class creating your own with the new method. But the performance would be horrible if your list grow too much. The indexOf method have O(n), so greater is the size of your array longer is the time you have to wait.

May be you should choose a different collection if you want access directly to the element. In your case, it elements stored in the collection are unique, you could use a Set.

On the other hand, a Set does not preserve the insertion order. I don't know if this is a think you have to care of.

And a Set just let you know if the element is contained into the collection.

Another collection that can be of your interest is the Map, this is a key-value collection.

But given that you have only keys this it seems not be your case.

Upvotes: 3

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

Upvotes: 3

Related Questions