【问题标题】:Null String from nowhere.不知从何而来的空字符串。
【发布时间】:2015-03-04 12:53:20
【问题描述】:

我有一个基本的ArrayList<Car>,我想用它来制作一个String[]。很简单,但是我的 String 不知从何而来,我不明白这个问题。
这是我的功能。

private String[] makeListOfCars(){
        Log.d("1st Car brand ", user.getCars().get(0).getBrand());
        Log.d("2nd Car brand ", user.getCars().get(1).getBrand());
        String result[] = new String[user.getCars().size()]; // Size > 0 because the user have at least one car here
        for(int i = 0 ; i < user.getCars().size() ; i++){
            result[i] += user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel();
            Log.d("Result ", result[i]);
        }
        return result;
    }

这是我得到的输出:

03-04 13:49:32.470 27216-27216/com.example.bla.app D/1st Car brand﹕ 宝马
03-04 13:49:32.470 27216-27216/com.example.bla.app D/2nd Car 品牌:沃尔沃
03-04 13:49:32.470 27216-27216/com.example.bla.app D/结果:nullBmw 335i
03-04 13:49:32.470 27216-27216/com.example.bla.app D/结果:nullVolvo V40

有人可以解释一下这个 null 是从哪里来的吗?

【问题讨论】:

  • 尝试:结果[i] = user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel(); (而不是 +=)

标签: java android list


【解决方案1】:

改变

result[i] += user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel();

result[i] = user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel();

附加“null”是因为result[i] 的初始值为null,当您将null 值连接到String 时,null 将变为"null" String。

【讨论】:

  • 太笨了……谢谢!我猜我在我的电脑前的时间太多了 :) 顺便说一句,答案很好。
猜你喜欢
  • 2023-02-15
  • 2013-07-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 2012-09-07
  • 2013-04-18
  • 2017-08-01
相关资源
最近更新 更多