将Servlet中的字符串与Java进行比较的奇怪问题

时间:2015-11-17 03:39:44

标签: java java-ee servlets

我的servlet存在这个奇怪的问题,如果我将变量传递给delete方法,但是如果我传递包含已经存在的元素的String,则无法删除对象的元素它就像一个魅力。这是我的代码:

delete方法:

public void delete(String t) {
    for (int i=0; i<list.size(); i++) {
        if(list.get(i).getTitre() == t) list.remove(i); 
    }
}

我的servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    String titre = (String) request.getParameter("T1");   
    Biblio b = (Biblio) request.getSession().getAttribute("list");     

    // here this works which means "titre" isnt null
    b.add(titre, "b", 1); 

    // this also works which means the delete method works correctly 
    b.delete("a"); 

    // this doesn't work, i get no error, the page load but the item is still there 
   b.delete(titre);

   request.getSession().setAttribute("list", b);    

   this.getServletContext().getRequestDispatcher("/WEB-INF/main.jsp")
       .forward(request, response);
}

编辑

问题很简单:我应该在equals方法中使用==代替delete

1 个答案:

答案 0 :(得分:3)

不要使用==比较字符串。如果区分大小写无关紧要,请使用equalsequalsIgnoreCase