0

I know how to use an ArrayList as an object like so:

ArrayList<Integer> numbers = new ArrayList<>();

However, as part of an assignment, I'm supposed to fill out the provided method:

private static ArrayList<Token> parse(String s) { }

How am I supposed to work with the ArrayList (which I'm guessing is a parameter) in this case?

2
  • Please provide the full description of what you need to do Commented Mar 16, 2016 at 5:27
  • The intention is for you to break up the input String s into tokens, and then store each token in the ArrayList which you then return to the caller. Commented Mar 16, 2016 at 5:28

3 Answers 3

2

The ArrayList is the return value from the parse method. The only parameter is a String which you need to break up into tokens, place each token in the ArrayList and then return the list.

How you break up the list is specific to its initial format which you haven't mentioned. The example below shows how the method might look if the String was comma separated:

private static ArrayList<Token> parse(String s) {
    String[] tokens = s.split(",");
    return Arrays.asList(tokens);
}

See the API docs for split asList:

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)

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

2 Comments

For now, this should be a comment (like the one I wrote).
Thanks, got it. I didn't go into further detail because I wanted to keep it concise and I just needed to know about the ArrayList
0

You can use java.util.Arrays for this

 public List<String> parse(String s) {
        return Arrays.asList(s.split(" "));
    }

If you want to return List of Token and It your custom class then you have to make for loop like this

public List<Token> parse(String s) {
    List<Token> tokenList = new ArrayList<>();
    String[] strings = s.split(" ");
    int length = strings.length;
    for (int i = 0; i < length; i++) {
        tokenList.add(new Token(strings[i]));
    }
    return tokenList;
}

Comments

0

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
        charList.add(str.charAt(i));
    }
    return charList;
}

Or if you need to split a string and on basis of some delimiter (example ','), then use

List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
return myList;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.