将List <object>转换为String将返回空结果

时间:2016-06-11 04:25:35

标签: java list

  

免责声明:我使用this Post作为List<Object>List<String>this Post对Java {{1}的参考字符串到JavaScript数组。

List<String>我希望以逗号分隔List<Seat>获取它的所有值,我尝试过这种方式

String

但是这给了我

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();
        }
    }
}
在控制台上,我是否犯了一些错误?在线工作代码为http://rextester.com/NDUGT61105

3 个答案:

答案 0 :(得分:2)

你没有附加迭代元素,见下文

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

查看toStringArrays

List实施

只需返回

strings.toString()

Arrays.toString(arr)

获得预期结果

答案 1 :(得分:1)

另一个选择,如果您使用的是Java 8,则使用StringJoiner:

https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html

答案 2 :(得分:0)

您忘了将数组元素追加到字符串缓冲区! 添加

sb.append(arr[i]);

在你准备字符串缓冲区的循环中,一切正常