user1264286
user1264286

Reputation: 21

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

Upvotes: 2

Views: 11351

Answers (6)

Jonathan Grandi
Jonathan Grandi

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

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53667

  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)

Upvotes: 0

Eng.Fouad
Eng.Fouad

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

Peter Lawrey
Peter Lawrey

Reputation: 533680

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)

Upvotes: 2

HJW
HJW

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

nwinkler
nwinkler

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

Related Questions