Reputation: 3793
I have a basic ArrayList<Car>
and I want to use it to make a String[]
. Pretty easy, but I get a null in my String from nowhere, and I do not understand the problem.
Here is my function.
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;
}
And here is the output I get:
03-04 13:49:32.470 27216-27216/com.example.bla.app D/1st Car brand﹕ Bmw
03-04 13:49:32.470 27216-27216/com.example.bla.app D/2nd Car brand﹕ Volvo
03-04 13:49:32.470 27216-27216/com.example.bla.app D/Result﹕ nullBmw 335i
03-04 13:49:32.470 27216-27216/com.example.bla.app D/Result﹕ nullVolvo V40
Can someone explain me from where this null come from?
Upvotes: 2
Views: 79
Reputation: 393856
Change
result[i] += user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel();
to
result[i] = user.getCars().get(i).getBrand() + " " + user.getCars().get(i).getModel();
The "null" is appended because the initial value of result[i]
is null, and when you concatenate a null
value to a String, the null
becomes the "null"
String.
Upvotes: 4