Reputation: 21
This is the code for trying to answer my question. I'm kind of new with ArrayLists. I used a for loop trying to read every element from the Arraylist and put it in the new String "full" but this won't compile. I need some editing. I don't think this code properly works. I used .add so that I can try adding the elements from the String List to String full. This is what tried to do so far.
public void String() {
ArrayList<Character> StringList = new ArrayList<Character>();
String full;
for(int i = 0; i < arr.length; i++) {
full.add(StringList[i]);
}
return full;
}
Upvotes: 2
Views: 11351
Reputation: 33
One effective way is to append each character to the string:
String myString = "";
for (Character c : myList) {
myString += c;
}
If myList.toString() gives: [a, b, c, d, e, f]
, then myString gives: abcdef
.
Upvotes: 1
Reputation: 53667
get(index)
of ArrayList to retrieve elements. Don't use it like array.
It will not work (eg StringList[i] is invalid use StringList.get(i))Upvotes: 0
Reputation: 117627
Normal way would be:
ArrayList<Character> StringList = new ArrayList<Character>();
StringList.add('H');
StringList.add('e');
StringList.add('l');
StringList.add('l');
StringList.add('o');
StringBuilder sb = new StringBuilder();
for(char c : StringList) sb.append(c);
System.out.println(sb.toString());
and here is another way to do it:
ArrayList<Character> StringList = new ArrayList<Character>();
StringList.add('H');
StringList.add('e');
StringList.add('l');
StringList.add('l');
StringList.add('o');
System.out.println(StringList.toString().replaceAll("[, \\[\\]]", ""));
OUTPUT:
Hello
Upvotes: 0
Reputation: 533680
I suggest
String
and use camelCase for variables.get(i)
Upvotes: 2
Reputation: 23443
There is no .add(String)
method in String class as far as i can remember.
But getting elements out of the ArrayList
, is this what you are looking for?
StringList.get(i);
Upvotes: 0
Reputation: 54467
Take a look at the StringBuilder
class, specifically the append
method:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html
Upvotes: 2