Scientist
Scientist

Reputation: 1464

ArrayList.add return String instead of boolean

We know that ArrayList.add returns boolean which indicates true or false.

Now a customization is required which says when we try and add null in arrayList it returns a custom string. Lets say for example it goes like this

public String add(Element e) {
   if (e == null) {
      return "StackOverflow";
   }
}

Now when I see that hierarchy List interface and Collection both have return type of add as boolean, there is no provision of overriding it.

please suggest how to proceed.

Upvotes: 1

Views: 771

Answers (3)

fasseg
fasseg

Reputation: 17761

You cannot override the add method with the same signature and return a different type. Since the add(T t) method is defined in the Collection interface as returning a boolean, all methods in the type hierarchy with the same signature must return a boolean.

You can however:

Change the Signature by adding more arguments:

public class MyList<T> extends ArrayList<T> {

    public String add(T t, String success, String error){
        if (add(t)) {
            return success;
        } else {
            return error;
        }
    }  
}

or

Change the Signature by using a different method name:

public class MyList<T> extends ArrayList<T> {

    public String addItem(T t){
        if (add(t)) {
            return "success";
        } else {
            return "error";
        }
    }  
}

or

Use a wrapper class that uses aggregation of an ArrayList to do the underlying operations. But you will have to implement all the methods get, add, size, etc

public static class MyArrayList<T> {
    private List<T> list;

    public MyArrayList() {
        this.list = new ArrayList<T>();
    }

    public String add(T t) {
        if (list.add(t)) {
            return "success";
        } else {
            return "error";
        }
    }

    public T get(int index) {
        return list.get(index);
    }
}

Upvotes: 1

J2B
J2B

Reputation: 1753

An alternative is to extend ArrayList (or another list implementation). But you need another name of the method, such as addElement.

public class MyArrayList<E> extends ArrayList<E> {
    public String addElement(E e) {
        if(e == null){
            return "StackOverflow";
        } else{
            super.add(e);
            return "Other";
        }
    }
}

@Test
public void addElement() throws Exception {
    MyArrayList<String> strings = new MyArrayList<>();
    assertEquals("StackOverflow", strings.addElement(null));
    assertEquals("Other", strings.addElement("other"));
}

Upvotes: 1

user180100
user180100

Reputation:

How about using:

String someMethod(Element e) {
     if (e == null) {
         return "StackOverflow";
     }
     theList.add(element);
     return "someString"
}

Upvotes: 4

Related Questions