convert string to arraylist in java

前端 未结 7 886
别跟我提以往
别跟我提以往 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<Character> interface like this:

    import java.util.AbstractList;
    import java.util.List;
    
    public class StringCharacterList extends AbstractList <Character>
    {
        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 <Character> l = new StringCharacterList ("Hello, World!");
    System.out.println (l);
    
    0 讨论(0)
提交回复
热议问题