0

I have a ArrayList with objects. When I try to get the properties of the objects in the ArrayList, the returned variable isnt exactly the value, which i before set to the variable. For example, when I try to compare the returned variable, variable type "String" isnt working. But when I print the value of the returned variable, it seems everything is working.

//Class: 
public class obj{
  public String name;

  public obj(String name){
    this.name = name;
  }
}

//Add to List:
ArrayList<obj> objs = new ArrayList<obj>(); 
objs.add(new obj("txt"));

//Get Value:
String name = objs.get(0).name;

//Not working:
if (name == "txt"){
  println("...");
}

//But working:
println(name); //same
if (name.charAt(0) == 116){ //"t" 
  println("working");
}

I tried:

  1. getter/setter methods are resulting in the same
  2. converting the returned var with a function which takes every char of the returned var, because the .length() is working, to a new String, containing every single character of the returned variable.
  3. creating a "toString()" method which returns the name of the object.
  • 1
    1) You are using `==` operator for string comparison which is wrong! You should use `String::equals`. 2) In order to be able to compare for equality two `obj` instances you need to override `equals` and `hashcode`. [Why to use String::equals](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java), [Why to override equals and hashcode](https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – dbl Jul 02 '19 at 11:34
  • 1
    Unrelated: A) study java naming conventions. Class names go UpperCamelCase B) use meaningful names `objs` is absolutely nothing-telling! – GhostCat Jul 02 '19 at 11:37

1 Answers1

0

In your code you check for Object equality:

//Not working:
if (name == "txt"){
  println("...");
}

you should use:

if (name.equals("txt"))
Würgspaß
  • 4,660
  • 2
  • 25
  • 41