Reputation: 19
I am working on a section of code for an assignment I am doing atm, and I am completely stuck with 1 little bit.
I need to convert the contents of an array list into a string, or the form of a string, which will be able to be imput into toString() in order for it to be printed to the screen.
public String toString(){
String full;
full = (this.name + this.address + "\n" + "Student Number = " + this.studentId);
for (int i = 0; i < cs.size(); i++) {
full.append(cs[i]);
return full;
The piece of above code is where i attempt to combine 3 varaibles and the contents of an array list into a single string with formatting.
Unfortunatly it creates an error "The type of the expression must be an array type but it resolved to ArrayList"
Thanks for any help.
Jake
Upvotes: 0
Views: 2479
Reputation: 32949
Just a note, since you don't put any spacers between each element of the ArrayList
it might be unreadable. Consider using Guava's Joiner class.
So instead of
for (...)
s.append(y);
if would be
a.append(Joiner.on(" ").join(yourList));
The Joiner is also more efficient than the for loop since it uses a StringBuilder
internally.
Upvotes: 0
Reputation: 573
Just use "cs.get(i)" in place of "cs[i]". as cs is an ArrayList not an Array.
and also use full = full + cs.get(i); and not full.append(cs.get(i));
as String type dont have a append method.
Upvotes: 0
Reputation: 66637
cs is array list, so you have to do get operation, not [] (which is for array access)
It should be like:
full.append(cs.get(i));
Not
full.append(cs[i]);
EDIT: As assylis said, full
should be StringBuilder
not just String
, because String doesn't support append()
method.
StringBuilder full = new StringBuilder()
;
Upvotes: 5
Reputation: 11572
You are attempting to access an ArrayList
as though it is a primitive array (using the square brackets around the index). Try using the get(int index)
method instead.
i.e.,
cs.get(i);
Upvotes: 2
Reputation: 272217
Apache Commons StringUtils has different varieties of join() methods that mean you don't have to write this yourself. You can specify the separator and even the prefix/suffix.
I would recommend you look at Apache Commons, not just for this but for lots of other useful stuff.
Upvotes: 2
Reputation: 62439
You cannot index an ArrayList
like an array, you need the get(index)
method. Even better, use the enhanced for
loop, since it's not recommended to index over a list, as the implementation may change to LinkedList
.
I also suggest using a StringBuilder
for efficiency:
public String toString() {
StringBuilder full = new StringBuilder();
full.append(this.name);
full.append(this.address);
full.append("\n");
full.append("Student Number = ");
full.append(this.studentId);
for (String s: cs)
full.append(s);
return full.toString();
}
Upvotes: 0