简体   繁体   中英

how can you take an ArrayList of chars and return all those elements from the ArrayList into a String

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

  • only use methods which are documented in Javadoc.
  • Use StringBuilder to build Strings, not ArrayList of Characters.
  • Don't call methods String and use camelCase for variables.
  • Don't access ArrayList as if it were an array, use 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
  1. Use lowerCamelCase as naming convention for name of variables and methods.
  2. Use 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))
  3. Read the Java Doc
  4. Always try to read and errors (if getting any)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM