ArrayList Limit to hold 10 Values

前端 未结 4 558
忘掉有多难
忘掉有多难 2021-01-04 17:51

I am using an ArrayList within my code which gets populated by a EditText field but I am wanting to limit the ArrayList so it can only

4条回答
  •  孤街浪徒
    2021-01-04 18:35

    ArrayList doesn't have a way of limiting the size; you could extend it to include a limit:

    public class FixedSizeLimitedArrayList extends ArrayList {
      @Override
      public boolean add(Object o) {
    
          int n=10;
          if (this.size() < n) {
              return super.add(o);
          }
          return false;
      }
    }
    
    
    

    Other options include:

    • Use an array, which is limited.
    • Modify the code that uses the list to enforce the limit (e.g. ArrayList Limit to hold 10 Values)
    • Find a list implementation that has a limit (some examples listed here): Any way to set max size of a collection?

    提交回复
    热议问题