• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList sorting

 
Steve Sutton
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am looking for a way to sort an arraylist. I am not sure exactly how to set this up, as I am pretty new to Java. I want to add one line of data elements to an arraylist something like this:
Arraylist a1 = new ArrayList;
ArrayList a2 = new ArrayList;
a1.fname = "joe";
a1.lname = "schmoe";
a1.address = "9999 broadway";
a1.phone = "999-999-9999";
a2.add(a1);
Should a1 really be an ArrayList? or something else?
I then want to be able to pass in a param like (lname, asc) to sort last name ascending. How do I set a1 up so that it has columns. I saw something similar to this done in the DictionaryEntry class, I just want to expand it to include more columns. Any help out there?
 
Joe Ess
Bartender
Posts: 9318
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Sutton:

Should a1 really be an ArrayList? or something else?

When you have a group of related variables, it's your first hint that you should create an object to contain and manage them.

How do I set a1 up so that it has columns.

An ArrayList is an array of Objects that can grow on its own. It does not have columns.


Any help out there?

The basics of the Java Language are covered in the
Java Tutorial.
You should check it out. It will answer the questions you have and many you will have. Bookmark the API Reference as well.
 
Joe Ess
Bartender
Posts: 9318
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And as for sorting, check out the Collections trail of the Java Tutorial. There's a learning curve to it, but once you've figured out how to sort one thing, you've pretty much mastered sorting everything.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve,
I think can you can create a People class to hold these personal info.
A sample People class would look like

you then use a ArrayList to hold those People objects and
Collections.sort(List,Comparator) to sort the list & display
the result by some code like

For the list to be sorted the way you prefered, you need to define a
comparision mecnhanism & pass it to the Collections.sort() as 2nd parameter.
assume you want to sorting by last name, you declare a LastNameComp class
that implements the Comparator interface to sort lastName,
eg.

please follow Joe's suggestion about related API documentation,
I hope the above code segments can help you but not interfering with
your learning.
[ October 24, 2003: Message edited by: chi Lin ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic