-1

I'm storing a string array in XML file and later retrieving it. I'm comparing an element of the array retrieved, arr[2] with "fail" and it's saying they're not equal but they are printing exactly the same letters ("f", "a", "i", "l"). It's going wrong when I'm either storing or retrieving I'm not sure which.

String s1 = "fail";
for (int i = 0; i < arr[2].length(); i++) {
    System.out.println(s1.charAt(i) == arr[2].charAt(i)); // true for all
    }

    System.out.println(s1 == arr[2]); //false

I have indicated the relevant parts in the code. This is the code for storing:

    DocumentBuilderFactory docFactory = 
              DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("items");
    doc.appendChild(rootElement);           
    Element hot = doc.createElement("hot");
    rootElement.appendChild(hot);
    for (String s: arr) {
        Element ele = doc.createElement("value");
        ele.appendChild(doc.createTextNode(s));  // Relevant part
        hotMap.appendChild(ele);        

This is the code for retrieving:

   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlFile);

        doc.getDocumentElement().normalize();        
        Node node = doc.getElementsByTagName(mapType).item(0);
        NodeList nodeList = node.getChildNodes();
        arr = new String[nodeList.getLength()];
        for (int n = 0; n < nodeList.getLength(); n++) {
            arr[n] = nodeList.item(n).getTextContent();  // Relevant part

        }
eager_coder
  • 47
  • 1
  • 8

1 Answers1

0

You should compare Strings by using .equals() since that tests if they are logically equivalent. Using == tests if they are the same object (which they are not). You could also use .equalsIgnoresCase() if you want the check to not be case sensitive.

MosaicOrange
  • 90
  • 12