Apps
Apps

Reputation: 3389

Search in Stack

I've a Java Stack created and some custom objects added to it. These objects contains unique id as one of their field. I need to get the index of that object in stack based on the unique name. Please find the example.

class TestVO{

 private String name;
 private String uniqueId;
//getters and setters
}
public class TestStack{
 public static void main(String args[]){
  TestVO vo1=new TestVO();
TestVO vo2=new TestVO();
TestVO vo3=new TestVO();

vo1.setName("Test Name 1")
vo1.setId("123")

vo2.setName("Test name 2");
vo2.setId("234");

Stack<TestVO> stack=new Stack<TestVO>();
stack.add(vo1);
stack.add(vo2);

//I need to get the index of a VO from stack using it's unique ID
}

}

Can someone please help me to implement this?

Upvotes: 2

Views: 3189

Answers (3)

Stephen C
Stephen C

Reputation: 719229

If you are going to base your notion of equality on the uniqueId field, then you should probably take steps to ensure that the field is properly initialized, and that it doesn't change once it has been initialized.

If you provide an unrestricted setter for the field, then you will get all sorts of broken behavior if some piece of code changes the field after the TestVO object has been inserted into a set or map.

Upvotes: 2

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47951

First, implement the hashCode and equals methods for the TestVO class:

class TestVO{

 private String name;
 private String uniqueId;

 public boolean hashCode() {
  if (uniqueId == null) return 0;
  return uniqueId.hashCode();
 }

 public boolean equals(Object o) {
  if (o instanceof TestVO) {
   TestVO other = (TestVO) o;
   return o.uniqueId.equals(uniqueId);
  }
  return false;
 }
//getters and setters
}

Please note that in the equals method you should add extra code to check that o.uniqueId is not null.

Now you can find the index of a TestVO object using its uniqueId using this code:

int index = stack.indexOf(vo1);

Upvotes: 4

Cristian Sanchez
Cristian Sanchez

Reputation: 32127

You can use the search method for Stack. It will return the distance of that object from the stack top. Hopefully that's good enough. You will need to define the equals method - which should be pretty easy - just do a comparison on your id field.

Java API Documentation

Upvotes: 2

Related Questions