简体   繁体   中英

Should I use an adapter class to share my arraylist?

I have an arraylist that I want normal users to only be able to GET information from and then I have an administrator account that I want to be able to do SET, SORT, and other methods to the arraylist. How do I share this array list with my administrator account and normal user accounts while also having different functionality to users depending on who they are. I came across the adapter class which if I understand correctly allows you to extend it and then only use the methods that you want to use and not have to override the other ones. Please let me know if this is correct. I don't have any code right now because I am still planning my project.

You can return a Collections.unmodifiableList() for the underprivileged consumers.

Or, if you want to be really restrictive and expose only certain ArrayList methods then you could consider creating your own class that has an ArrayList within. You could further subclass this with the extra methods that you want to expose to privileged consumers.

Something like this:

public class MyList<T> {
  ArrayList<T> arrayList;
  public T get(int index) {
    return arrayList.get(index);
  }
}

public class MyModifiableList extends MyList<T> {
  public boolean add(T object) {
    return arrayList.add(object);
  }
}

Your object would no longer be a List, so it would not be able to take advantage of good stuff like Collections.sort(list).

You can make a list readonly by using Collections.unmodifiableList()

You don't give much details in your question, but here is an example of how it could work. Assuming that you have an object that allows you to get a hold of an array based on a UserType enum:

public List<Object> getMyArray(UserType type) {

    if (type == UserType.ADMIN) {
        return _myList;
    }
    else {
        return Collections.unmodifiableList(_myList);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM