Jason Khalili
Jason Khalili

Reputation: 101

Using an ArrayList in Java

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?

Upvotes: 0

Views: 640

Answers (3)

JamesB
JamesB

Reputation: 7894

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...)

Upvotes: 2

FallAndLearn
FallAndLearn

Reputation: 4135

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;

Upvotes: 0

Kishan Vaghela
Kishan Vaghela

Reputation: 7938

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;
}

Upvotes: 0

Related Questions