Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Suggestion

 
Harathi Rao
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have a typical situation where i have setter and getter methods like this
Item item = new Item();
item.setValue1()
Item.getValue1()
.
.
.
.
item.setValue6()
item.getValue6()

And I got a List data = {"hello","good","morning"};

I need to set these values and get them using above setter and getters..
item.setValue1(data.get(0));
item.setValue2(data.get(1));

Now, is there a simple way to do this... by using for loop or any such logic...


Thanks in anticipation!
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If those are really your method names, why not make them indexed?

So instead of the 6 setValue methods and 6 getValue methods, have one of each:

Of course, if you store your values in an array as well, you can just use the array index; it will throw an IndexOutOfBoundsException of its own.
Do remember though that in Java, arrays are 0 based. So you might want to use "array[index - 1]" to keep your methods 1 based.
 
Srikanth Basa
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can plan to use Java reflections, if you are allowed to.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic