Hamza Tahiri
Hamza Tahiri

Reputation: 506

Wierd issue comparing Strings in Servlets with Java

I have this wierd problem with my servlet, I can't delete an element of an object if I pass variable to the delete method, but if I pass a String that contains an element that already exists it works like a charm. Here's my code:

The delete method:

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

My 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);
}

EDIT

The issue was quiet simple: I should have used equals instead of == in my delete method.

Upvotes: 0

Views: 69

Answers (1)

jmcg
jmcg

Reputation: 1567

dont compare Strings using ==. use equals or equalsIgnoreCase if case sensitivity does not matter

Upvotes: 3

Related Questions