0

So, I'm trying to compare a string to an instance variable of another class, and I can't think of a way to do this for all objects of the said class. I know for sure that if the method where this occurs is running, I have 4 objects of the class that contains the instance variable. The goal is to compare the string the user gives me, and if it is equal to the one of a previously defined object, change another instance variable in that object. In sudo-code it would be something like this:

if (colourInput == colourofAnyObjectOfTheClass)
   sizeOfThatObject = sizeInput;
else
   new Object(colourInput, sizeInput);

And I've previously defined what colourInput and sizeInput are. How can I go about implementing this in Java?

uname22
  • 17
  • 4
  • possible duplicate of [Java string comparison?](http://stackoverflow.com/questions/995918/java-string-comparison) – upog Nov 04 '13 at 13:14

2 Answers2

1

When comparing Strings, you should use the String#equals() method, not the == operator.

if (colourofAnyObjectOfTheClass.equals(colourInput)) {
    sizeOfThatObject = sizeInput;
} else {
    new SomeObject(colourInput, sizeInput);
}
Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

You should consider creating some sort of repository of instances of your class that is class which will manage creation of object so it can keep track of them.

class MyEntityRepository {
    private List<MyEntity> entities;

    public MyEntity createOrUpdate(String color, Integer size) {
         MyEntity entity = findByColor(color);
         if (entity != null) {
             entity.setSize(size); 
         } else {
             entity = new MyEntity(color, size);
             entities.add(entity);
         }
         return entity;
    } 

    private MyEntity findByColor(String color) { ... }
}  

If you have a lot of entities you may create some sort of index, for example store Map<String, MyEntity> which maps keys to entities and use it to speed up search.