1

For a string "a3tx2z" The output of this should be "attttxzzz", or for "12x" it should be "2xxx". I checked everything and they work. but when i want to print "ttt" in the place of 3, there is a java.lang.UnsupportedOperationException at line 28 l.add(i, s1);. What is wrong here?

package xyz;

import java.util.Arrays;
import java.util.List;

public class xyz {

    public static void main(String[] args) {

        xyz n = new xyz();
        n.blowup("a3tx2z");

    }

    public String blowup(String str){

        String[] array = str.split("");
        List<String> l = Arrays.asList(array);

        for(int i=0; i<l.size(); i++){
            String s1 = l.get(i);
            if(s1.matches("-?\\d+(\\.\\d+)?")){
                String s2 = l.get(i+1);
                if(!(s2.matches("-?\\d+(\\.\\d+)?"))){
                    int t = Integer.parseInt(s1);
                    while(t>0){
                       l.add(i, s1);
                       t--;
                    }
                }
            }
    }
        for(String x: l){
            System.out.print(x);
        }
        return "";
    }

}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
user3367020
  • 11
  • 2
  • 7
  • Be careful; it's not a java.util.ArrayList, but a [`java.util.Arrays.ArrayList`](http://stackoverflow.com/a/4792194/899126)! – Chris Forrence Nov 10 '14 at 20:42
  • Duplicated: http://stackoverflow.com/questions/2965747/why-i-get-unsupportedoperationexception-when-trying-to-remove-from-the-list – Kohei Mikami Nov 10 '14 at 20:44

1 Answers1

4

You're getting a List returned by Arrays.asList, but it's just a wrapper around an array, so you can't add anything to it.

Returns a fixed-size list backed by the specified array.

If you must add to it, then create another ArrayList out of that list.

List<String> l = new ArrayList<String>(Arrays.asList(array));
rgettman
  • 176,041
  • 30
  • 275
  • 357