java - How do i access a specific object from with in the class it was created from -


im not going paste whole entire code here problem. keep things simple ill make code right here problem.

okay have class called "exampleclass" has integer variable called "number" example , "number" has , set method. question is: if have multiple objects of "exampleclass" how specific object out of multiple objects can access specific object inside "exampleclass".

"exampleclass" below

   public class exampleclass{      public int number;      public int getnumber() {         return number;     }      public void setnumber(int number) {         this.number = number;     } } 

assuming number makes instance of class "unique" purpose of comparison, should consider overriding equals , hashcode methods.

that way, you'll able find instances of class within collection such arraylist using indexof(object o);

for example:

public class exampleclass {     private int number;      public exampleclass(int number)     {         this.number = number;     }      public int getnumber()     {         return number;     }      public void setnumber(int number)     {         this.number = number;     }      @override     public boolean equals(object other)     {         boolean isequal = false;          if (other instanceof exampleclass)         {             exampleclass otherec = (exampleclass)other;              isequal = number == otherec.number;         }          return isequal;     }      @override     public int hashcode()     {         return number;     } } 

and

public static void main(string[] args) {     list<exampleclass> list = new arraylist<exampleclass>();      exampleclass ec1 = new exampleclass(1);      list.add(ec1);     list.add(new exampleclass(3));     list.add(new exampleclass(102));      system.out.println(list.indexof(new exampleclass(3)));     system.out.println(list.indexof(new exampleclass(1)));     system.out.println(list.indexof(ec1));     system.out.println(list.indexof(new exampleclass(5)));  } 

will produce following output:

1 0 0 -1 

please here more information on why should override equals , hashcode objects want store in collections:

why need override equals , hashcode methods in java?


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -