I have to split a line that has been stored in a String[], and then place the parts in an ArrayList.

Currently I am doing the following:

(vehicles is the origional String[],
details is the String, detail_split is the ArrayList)

for (int y = 0; y < vehicles.size(); y++) {
				details = (String)vehicles.get(y);
				detail_split = (ArrayList)details.split("$$", -1);

When I try the above code, Eclipse says:"Cannot cast from String[] to ArrayList"

What am I doing wrong?

Is there a better way for me to do it?

Recommended Answers

All 5 Replies

The split returns an array. And you try to cast it to ArrayList.
From the String get the String [] array using the split method.
Then loop through the array and add its elements to an ArrayList

List<String> list = Arrays.asList(string.split());

Thanks, both of you.

Slightly offtopic:
An ArrayList splits the values it contains with commas. Some of the values I put in that ArrayList contain commas. This seems to be messing things up(I think that's the problem)

I'm not asking you to give me the code for this, just want to know if it is possible to tell the ArrayList not to use commas, but to use something else(e.g. ! or $)

Huh? An "ArrayList" doesn't do any splitting whatsoever and what you are splitting on is "$$". Are you telling me that you have a String such as


And you want to get three list's out of it?

If you want one list that contains "a,b,c" - "d,e,f" - "g,h,i" then use the line above (P.S. you may have noticed I am using List, and not ArrayList. Unless you have some specific method from ArrayList you need to use, I would suggest you do the same.).

If you want three Lists as follows
List1 - "a" - "b" - "c"
List2 - "d" - "e" - "f"
List3 - "g" - "h" - "i"

Then use the new for loop to loop over the "split" used above and use the above statement with "," as the pattern within that loop.

The strings in the ArrayList(and yes, I have to use an ArrayList) are names and surnames, along with the age, of people. The name and surname are received as one record: Surname, Name. Thus, the ArrayList looks like this:

surname, name, age$$surname, name middleName, age


There are some variables, though. One person could have his title in the string as well, so I am never sure how many commas there will be in each line.

Regardless, my origional question has been answered, and I am marking this as solved. If I need help with something else, I will start a new thread.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.