• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting Java vector by an object  RSS feed

 
Ndoro Permai
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys i need to sort a java vector, but i dont know how to do it, can you please help me guys?
i got three vector called
-vpayment
-vdate
-vcode
and i need to sort this three vector just only based by vcode
how can i do that??
sorry because im just a beginner,,,
need help ASAP guys
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, don't use Vector unless you have no choice because you're dealing with legacy code that requires it. ArrayList is the preferred replacement.

If you want to sort it, you'll need to either have the objects you put into it implement Comparable, or you'll need to define a Comparator class. Either way, you just need to implement one method that compares two of your objects and determines which one is "less" based on whatever rules you define. Then you can call Collections.sort(), or the other sort() signature that takes a Comparator.

For more details, google for java comparable tutorial.

And welcome to the Ranch!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ndoro Permai wrote:Guys i need to sort a java vector, but i dont know how to do it, can you please help me guys?
i got three vector called
-vpayment
-vdate
-vcode
and i need to sort this three vector just only based by vcode


Actually, that's bad.

A better way to do it would be to define a class that has payment, date, and code fields, and then create a single List of these objects. The whole "parallel lists" approach is very anti-OO, and will just make your work a lot harder. The approach I described in my previous reply won't work if you have 3 separate lists like this.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ndoro Permai wrote:Guys i need to sort a java vector, but i dont know how to do it, can you please help me guys?

Well, Java has two basic methods of ordering objects:
1. Make the objects you want to sort Comparable.
2. Create a Comparator that provides the ordering you want.
Then, sorting is usually a matter of calling Collections.sort() (for a List), or putting your objects into a SortedSet, such as a TreeSet; the advantage of the latter being that your objects will always be sorted.

need help ASAP guys

EaseUp (←click). Urgency is your problem, not ours.

Winston
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!