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;
}
看一下StringBuilder
类,特别是append
方法: http : //docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html
I suggest
String
and use camelCase for variables. get(i)
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
.
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);
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
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.