检查对象是否包含在链表中 [英] Checking if an object is contained within a linkedlist

查看:164
本文介绍了检查对象是否包含在链表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序,在主要方法中,我向链接列表中添加了一个值。当我尝试通过一种检查先前添加的值是否在列表中的方法来添加另一个值时,它不会将该值识别为在列表中,并且如果不在列表中,则会执行该操作。为什么该程序无法识别列表中的对象?

I have this program and in the main method I add a value into a linked list. When I try to add another value through a method that checks to see if the value added previously is in the list, it does not recognize the value as being in the list and does the operation it should do if it is not in the list. Why is this program not recognizing the objects that are put into the list? the program does not recognize "h" has been added to the list.

import java.util.LinkedList;
import java.util.List;


public class Menu {
    LinkedList <LinkedList> mainMenuItems = new LinkedList <LinkedList> ();


public void  Menu(){

}

public boolean addMainMenuItem(String newItem, String existingItem, int position){
    LinkedList <String> subMenuItems = new LinkedList <String> ();
    if (! mainMenuItems.contains(existingItem)){
        subMenuItems.addLast(newItem);
        mainMenuItems.add(subMenuItems);
        return true;}
    if (mainMenuItems.contains(existingItem)){
        subMenuItems.addLast(newItem);
        int existingIndex = mainMenuItems.indexOf(existingItem);
        if (position == 1){
    LinkedList temp = new LinkedList <LinkedList>();
    temp = mainMenuItems.get(existingIndex+1);
    mainMenuItems.remove(existingIndex+1);

    mainMenuItems.add(existingIndex + 1, subMenuItems);
    mainMenuItems.add(existingIndex +2, temp);

    }


        if (position == -1){
            mainMenuItems.add(existingIndex, subMenuItems);}
    return true;    }
    return false;}


public boolean deleteMainMenuItem(String item){
    if (mainMenuItems.contains(mainMenuItems.indexOf(item))){
    mainMenuItems.remove(mainMenuItems.indexOf(item));
    return true;}
    else{
    return false;}}

public static void main(String[] args){
    Menu b = new Menu();
    b.addMainMenuItem("h", "b", 1)  ;

b.addMainMenuItem("hi", "h", 1) ;
b.addMainMenuItem("i", "h", 1)  ;
System.out.println(b.mainMenuItems.get(0));
System.out.println(b.mainMenuItems.get(1));
b.deleteMainMenuItem("hi");
System.out.println(b.mainMenuItems.get(2));
System.out.println(b.deleteMainMenuItem("hi"));


}







}


推荐答案

您正在测试 LinkedList< LinkedList> ,由于字符串与LinkedList的类型不同,因此总是为假。如果您确实需要对此进行测试,那么您将不得不遍历主LinkedList中的每个项目,并且其中的任何一个都对String进行测试。

You are testing if a String is contained by a LinkedList<LinkedList> which will always be false because a String is not the same type as a LinkedList. If you really need to test this, then you're going to have to iterate through each item in the main LinkedList and test of the String is held by any of them.

这篇关于检查对象是否包含在链表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆