Arshad Ali Arshad Ali - 5 months ago 8
Java Question

Converting List<Object> to String returns empty results


Disclaimer : I'm using this Post, as reference for
List<Object>
to
List<String>
and this Post for Java
List<String>
of strings to a JavaScript array.


I've
List<Seat>
and I want to get all values of it in a comma separated
String
, I tried in this way

import java.util.*;
import java.lang.*;

class Rextester
{

public Rextester(){
Seat seat1 = new Seat();
seat1.setSeatNumber(1);

Seat seat2 = new Seat();
seat2.setSeatNumber(2);

Seat seat3 = new Seat();
seat3.setSeatNumber(3);


List<Seat> seatList = new ArrayList<Seat>();
seatList.add(seat1);
seatList.add(seat2);
seatList.add(seat3);
Utility util = new Utility();
String stringSeats = util.toJavascriptArray(seatList);
System.out.println("JavaScriptArray is " + stringSeats);
}

public static void main(String args[])
{
new Rextester();

}



private class Seat {

private Integer seatNumber;

public Integer getSeatNumber() {
return this.seatNumber;
}

public void setSeatNumber(Integer seatNumber) {
this.seatNumber = seatNumber;
}
public String toString() {
return ""+ seatNumber;
}
}

private class Utility {

public String toJavascriptArray(List<Seat> listSeats){
List<String> strings = new ArrayList<String>();
for (Seat object : listSeats) {
strings.add(object != null ? object.toString() : null);
}
String[] arr = new String[strings.size()];
arr = strings.toArray(arr);
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr.length; i++){

if(i+1 < arr.length){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
}
}


but this gives me

JavaScriptArray is [,,]


on console, am I making some mistakes? an online working code is http://rextester.com/NDUGT61105

Answer

You didn't append iterated element, see below

        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]); // add this
            if (i + 1 < arr.length) {
                sb.append(",");
            }
        }

have a look at the toString implementations of Arrays and List

Simply you can return

strings.toString()

or

Arrays.toString(arr)

To get the String in your expected format