0

I have a List as per following:

private void someMethod () {
    String str= "someStrParam";
    private int theCount = 0;
    List<String> itemList = getListMethod(str);
      if (theCount < itemList.size()) {
        return itemList.get(theCount++);
        } else {
        return null;
      }
 }

Question: As soon as a List item is added to the List in the getListMethod, how can I access it immediately in the someMethod without waiting for the next item to be added? Or is there way a way we put a monitor on getListMethod so that, as soon as the an item is added there, we can query the itemList ?

Ajay Kumar
  • 2,906
  • 3
  • 23
  • 46
  • 1
    Here's a pretty similar question. You may find some interesting ideas for implementing your own listener there. https://stackoverflow.com/questions/16529273/how-to-add-listener-on-arraylist-in-java and also here https://stackoverflow.com/questions/19509717/want-to-notify-on-when-an-item-is-inserted-into-arraylist-using-callback-in-java – Gonen I Oct 21 '21 at 20:04

2 Answers2

4

You can use the PropertyChangeSupport with your custom list:

class MyList<T> {
    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
    private final List<T> itemList = new ArrayList<>();

    public void addName(T name) {
        itemList.add(name);
        propertyChangeSupport.firePropertyChange("item", null, Collections.unmodifiableList(itemList));
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        propertyChangeSupport.addPropertyChangeListener(l);
    }

    public void removePropertyChangeListener(PropertyChangeListener l) {
        propertyChangeSupport.removePropertyChangeListener(l);
    }
}

Usage:

 public static void main(String[] args) {
        MyList<String> myBean = new MyList<>();
        myBean.addPropertyChangeListener(evt -> System.out.println("Hello"));
        myBean.addName("Hello");
    }
PavlMits
  • 523
  • 2
  • 14
0

To simplify, to test the usage and to understand answer given by @PavlMits, I tried like this:

public class MyListUsage {
     public static void main(String[] args) {
            MyList<String> myList = new MyList<>();
            myList.addPropertyChangeListener(evt -> callThisOnAddItemToList ());
            myList.addName("foo");
            myList.addName("bar");
            myList.addName("blah-blah");
        }
     
     private static void callThisOnAddItemToList () {
         System.out.println("Do something here as and when an item added to list ......");
     }
}

And I got the below output:

Do something here as and when an item added to list ......
Do something here as and when an item added to list ......
Do something here as and when an item added to list ......
Ajay Kumar
  • 2,906
  • 3
  • 23
  • 46