Illep
Illep

Reputation: 16841

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 resolve this.

Upvotes: 0

Views: 591

Answers (3)

hanung
hanung

Reputation: 358

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.

Upvotes: 0

Brett Walker
Brett Walker

Reputation: 3576

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.

Upvotes: 1

Bozho
Bozho

Reputation: 597016

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
}

Upvotes: 1

Related Questions