Why do I get an UnsupportedOperationException when trying to remove an element from a List?

后端 未结 17 2013
后悔当初
后悔当初 2020-11-22 07:43

I have this code:

public static String SelectRandomFromTemplate(String template,int count) {
   String[] split = template.split(\"|\");
   List         


        
17条回答
  •  旧时难觅i
    2020-11-22 08:14

    You can't remove, nor can you add to a fixed-size-list of Arrays.

    But you can create your sublist from that list.

    list = list.subList(0, list.size() - (list.size() - count));

    public static String SelectRandomFromTemplate(String template, int count) {
       String[] split = template.split("\\|");
       List list = Arrays.asList(split);
       Random r = new Random();
       while( list.size() > count ) {
          list = list.subList(0, list.size() - (list.size() - count));
       }
       return StringUtils.join(list, ", ");
    }
    

    *Other way is

    ArrayList al = new ArrayList(Arrays.asList(template));
    

    this will create ArrayList which is not fixed size like Arrays.asList

提交回复
热议问题