简体   繁体   English

如何检查LinkedList中的索引处是否存在元素

[英]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. 我有一个叫做Modul的类,并且正在将它们的元素添加到我的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. 现在,我想编写一个方法,在其中输入一个Integer并检查列表的索引处是否有一个元素或该元素是否为空。 if there is a element i will return it and if not i want to return null and an error message. 如果有一个元素,我将返回它,如果没有,我想返回null和错误消息。

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. 我曾经考虑过使用if语句,但最终想不出一种检查元素是否存在的方法。 Now I thought of using try-catch but I don't know what kind of error I would need to catch. 现在,我想到了使用try-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 ? 对链表进行索引会浪费内存,如果您坚持要为此花费O(n)才能到达链表中的该索引,则可以向Node int索引添加属性,并通过构造器Node()增加该值并进行设置实例达到该值后,在开始时删除节点会发生什么小问题呢? 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 是的,很大的问题是整个列表必须重新索引,这使得从Start删除的过程是O(1)一个O(n)操作

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 您可以使用技巧来为其编制索引,也可以给人一种被索引的错觉,只是在您请求list(6)时不要这样做,迭代器计数6个节点,这些节点从0开始并在该节点处停止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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