Arraylist Java interface program

System.out.println("Enter the appointment ID to see the full details :");
int y=in.nextInt();
int r;
for(r=0;r<count;r++)
{
    if(all.get(r).getID()==y)
    {
         all.get(r).display();
    }
}

      

I am using this code to get the complete information that was entered using the get statement and the display function. This is a small part of my program. I was wondering if there is another way to do this.

+3


source to share


2 answers


Best used HashMap<Integer,DetailsClass>

instead of ArrayList.

Then, instead of a loop, you just write:

HashMap<Integer,DetailsClass> map = new HashMap<>();

...

if (map.containsKey(y)) {
    DetailsClass details = map.get(y);
    details.display();
}

      



This makes the code simpler and more efficient, since looking up the key in the HashMap takes the expected constant time, while looking up the List takes linear time.

If you must use ArrayList

, at least leave the loop as soon as you find the object you were looking for:

int y=in.nextInt();
for(int r=0;r<count;r++)
{
    if(all.get(r).getID()==y)
    {
         all.get(r).display();
         return; // or break; depending on where this for loop is located
    }
}

      

+4


source


Never iterate over List

the index. You don't know that internal implementation List

and cyclization can lead to complexity O(n^2)

.

I would suggest the following:

System.out.println("Enter the appointment ID to see the full details :");
final int y = in.nextInt();
for(final Thing thing : all) {
    if(thing.getID() == y) {
         thing.display();
    }
}

      



Or, if you can use Java 8, then:

all.stream()
        .filter(t -> t.getID() == y)
        .findFirst()
        .ifPresent(Thing::display);

      

+2


source







All Articles