convert string to arraylist in java

前端 未结 7 979
别跟我提以往
别跟我提以往 2020-12-10 01:03

How to convert a String without separator to an ArrayList.

My String is like this:

String str = \"abcd...\"
         


        
7条回答
  •  臣服心动
    2020-12-10 01:49

    If you dn not need to modify list after it created, probably the better way would be to wrap string into class implementing List interface like this:

    import java.util.AbstractList;
    import java.util.List;
    
    public class StringCharacterList extends AbstractList 
    {
        private final String string;
    
        public StringCharacterList (String string)
        {
            this.string = string;
        }
    
        @Override
        public Character get (int index)
        {
            return Character.valueOf (string.charAt (index));
        }
    
        @Override
        public int size ()
        {
            return string.length ();
        }
    }
    

    And then use this class like this:

    List  l = new StringCharacterList ("Hello, World!");
    System.out.println (l);
    

提交回复
热议问题