10

I want to create an ArrayList of character objects based off the characters in a string of letters. But, I can't seem to figure out how to fill that ArrayList to match the String. I've been trying to have it iterate through the string so that later, if I change the content of the string it'll adjust. Regardless, no matter what I do I'm getting some sort of syntax error.

Could anybody please guide me in the right direction? Thanks a bunch!

import java.util.ArrayList;
import java.text.CharacterIterator;   //not sure if this is necessary??

public class Test{

//main method

     String words = new String("HELLO GOODBYE!");
     ArrayList<Character> sample = new ArrayList<Character>();

     for(int i = 0; i<words.length(); i++){
         sample.add((char)Character.codePointAt(sample,i));
     }
}
3
  • 3
    char[] charArray = words.toCharArray(); Commented Jul 13, 2014 at 0:46
  • 3
    In your case sample.add(words.charAt(i)); should work Commented Jul 13, 2014 at 0:46
  • would this still add them as character objects?? Commented Jul 13, 2014 at 0:54

2 Answers 2

16

In your case, words.charAt() is enough.

  import java.util.ArrayList;

  public class Test{

       String words = new String("HELLO GOODBYE!");
       ArrayList<Character> sample = new ArrayList<Character>();

       for(int i = 0; i<words.length(); i++){
           sample.add(words.charAt(i));
       }
  }

Read more: Stirng, Autoboxing

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! would this still be considered as adding character objects?
1

This code adds all the characters in a character array to an ArrayList.

Character[] letters = {'a', 'b', 'c', ...};
List<Character> array = new ArrayList<Character>();
array.addAll(Arrays.asList(letters));

1 Comment

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.