We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Storing char in ArrayList
Page Index Toggle Pages: 1
Storing char in ArrayList (Read 499 times)
Storing char in ArrayList
Jun 20th, 2008, 4:41pm
 
I tried to store a char in ArrayList and it generated an error.
Code:

ArrayList let = new ArrayList();
String s_line = "This is a test";
for(int i=0;i<s_line.length();i++)
{
char ch = s_line.charAt(i);
let.add(ch);

}


How do I get around this problem?
Re: Storing char in ArrayList
Reply #1 - Jun 20th, 2008, 7:04pm
 
a 'char' is a primitive type, like int, float, and byte. an ArrayList can only hold objects. Character, Integer, Float, and Byte are the object versions of these classes. you can wrap a primitive type as an object like so:

Code:
ArrayList let = new ArrayList();
String s_line = "This is a test";
for(int i=0;i<s_line.length();i++)
{
char ch = s_line.charAt(i);
Character co = new Character(ch);
let.add(co);
}


though storing chars in an ArrayList is a pretty inefficient way to work (which is why there's a distinction between primitive types and objects in Java), so i'd recommend using an array instead, e.g.:

char[] c = s_line.toCharArray();

then you can use the usual array method (expand(), .length,  append()) on the array.
Re: Storing char in ArrayList
Reply #2 - Jun 21st, 2008, 5:21am
 
Thanks
Page Index Toggle Pages: 1