Checking if an object is contained within a linkedlist

久未见 提交于 2019-12-26 15:06:14

问题


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"));


}







}

回答1:


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.



来源:https://stackoverflow.com/questions/25955973/checking-if-an-object-is-contained-within-a-linkedlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!