简体   繁体   中英

How can I check if an element exists at an index in a LinkedList

I have class called Modul and am adding elements of them to my LinkedList. Now I want to write a method where I input an Integer and check if there is an element at that index of the list or if it is empty. if there is a element i will return it and if not i want to return null and an error message.

I have thought of using an if-statement, but ultimately can't think of a method that checks whether or not an element is present. Now I thought of using try-catch but I don't know what kind of error I would need to catch.

import java.util.LinkedList;

public class Modulhandbuch {
    private String nameStudienordnung;
    private LinkedList<Modul> liste;

    public Modulhandbuch(String nameStudienordnung) {
        this.nameStudienordnung = nameStudienordnung;
        liste = new LinkedList<Modul>();
    }

    public void einfuegenModul(Modul m) {
        liste.add(m);
    }

    public int anzahlModule() {
        return liste.size();
    }

    public Modul ausgebenModul(int i) {
        try {
            return liste.get(i);
        }catch() //I don't know what error i would need to catch
    }

}

You get a null pointer exception if you give the method an integer value that is bigger than the size of the list, because this index does not exist, so you need to check that. The method below correctly handles that case.

public Modul ausgebenModul(int i) {
    if (i >= anzahlModule)
        return null;
    else
        return liste.get(i);
}

indexing a linked list is waste of memory it takes O(n) to get to that index in a linkedList if you insist on this then you can add a property to the Node int index and through the constructer Node() increase this and set that instance to that value now there are few little problems to this what happens when you remove a Node at the Start ? yeah big problem the whole list must be reindexed thats makes the process of remove from Start which is O(1) a O(n) operation

you can do a trick to index it or give an illusion of been indexed is just don't do it when you ask for list(6) the iterator counts 6 Nodes Starting with 0 and stop at that Node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM