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"));
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…