开发者

how to get the first element from a List - Beginner

I have a List <Hotel> object, and it has 1o elements in it. Now i need to print all the values stored in this List object.

The code i tried is as follows;

List <Hotel> hotels;
... i have included the getters and setters for the above List of hotels

int x = getHotels.size(); 
System.outprintln("SIZE = "+ x + " hotel index 2 name " + getHotels.get(2).getHotelName());

When i execute the program the x value gets displayed, but when i add getHotels.get(2).getHotelName() i get a Nullpoint Exception. How do i reso开发者_StackOverflowlve this.


This means that the element at index 2 (which is the 3rd element) is null. Iterating collections is usually done with the for-each loop:

for (Hotel hotel : hotels) {
   // do something with each hotel
}


List, like many other things, in Java are zero-based. If the List is of size 2 then getHotels.get(0) and getHotels.get(1) return the first and second elements in the list.


Depending on the List implementation, for example ArrayList permits null elements.

So it might be some null elements on your List, even if it has 10 members.
To ovoid null pointer exception, simply check if current element is a null.

for (Hotel hotel: hotels) {
    if (hotel != null) {
        // do something
    }
}

Another cause might be your hotel.getHotelName() returns null,
Make sure you have set the hotel name at index 2 before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜