2 dimensional ArrayList sorting.

Hello,
let me first tell you a bit about my scenario, I am creating an auction program running over RMI, my server passes my client an arraylist of auctions (ListOfAuctions), and these auctions are represented by an arraylist themselves (description, start time, current price, etc)
Where I'm struggling, is I have to be able to sort the top level auctions arraylist (ListOfAuctions), based on an integer element within the individual auctions.
The element I need to sort by is in the same position in the Auction array each time.
Any ideas would be much appreciated, i'm pretty terrible with sort algorithms!
Auction is like so:
element [0] (String)
element [1] (String)
element [2] (Integer)
element [3](Integer)
time Left [4] (Integer) <-- I need to sort 'ListOfAuctions' by this.
element [5] (Integer)
etc.
ListOfAuction is simply an arraylist of the above. I'm too deep rooted into arraylists to use hashtables now so please, no suggestions for using those.
Thanks in Advance
Andy.

I'm committed to this way though, unfortunately..You should tell the one responsible for your project
that by not creating an Auction class and
using java.util.Collection's built-in sort
algorithms, you are creating something that will end
up taking more time to maintain (and even to finish!)
than just doing it the OO-approach and rewriting it
now!Exactly. The way you're trying to do it, you'll have to not only write the code to compare the auctions, but also implement your own sorting algorithm. If you ever need to add another attribute to your auctions, you'll have to make big changes to your sorting algorithm, as well as all the code that handles those lists. If you had an Auction class, adding another attribute wouldn't affect the sorting at all! (unless they were going to be sorted according to that attribute also). It also wouldn't affect any of the code that handles that list of Auctions, since the data associated with auctions is abstracted away, and you don't have to touch it!

Similar Messages

  • ArrayList sort() compareTo()..

    Hi All,
    Yep, I've already looked at dozens of "examples" of trying to use:
    Collections.sort(ArrayList)
    or
    Collections.sort(ArrayList, compare)
    But I still can't figure-out how to construct a, simple, compareTo() for
    my ArrayList. :-\
    If someone could point to a relevent example, or just show me
    how to do it that would be great! :-)
    My ArrayList Object looks like this:
    class TypeObject
    public int location;
    public String name;
    public int type;
    I want to sort on 'location', and it can be 'int' or 'Integer', whatever is
    easier. And I'd like to use the "older" Java, that is no "<>".
    Thanks for your help! :-)
    Joe S.

         class CustomComparator implements Comparator {
              public int compare(Object o1, Object o2) {
                   TypeObject to1 = (TypeObject)o1;
                   TypeObject to2 = (TypeObject)o2;
                   int thisVal = to1.getLocation();
                   int anotherVal = to2.getLocation();
                   return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
         }Kaj

  • ArrayList sort

    Hi everyone,
    I have a problem I need to sort an ArrayList, that contains other
    ArrayList:
    ArrayList row=new Arraylist;
    ArrayList col=new ArrayList;
    col.add(aString);
    col.add(anAge);
    col.add(aDate);
    row.add(col);
    Lets suppose that we have 3 rows:the
    first ["John",23,01/01/1970]
    second["Mary",22,02/02/1980]
    third ["April",34,05/01/1969]
    I want to sort this, I want this order in the row ArrayList:
    ["April"...]
    ["John"...]
    ["Mary"...]
    I will appreciate your help.
    Thanks
    Manuel Rojas

    You probably would want to use the following class
    java.util.Collections and implement the following method.
    Collections.sort(List yourList, Comparator yourComparator);
    You will need to implement yourComparator.
    If you have not done this it is not too hard, and is a good thing to learn, teaches many java fundimetals.

  • Sorting ArrayList multiple times on Multiple Criteria

    I have an arraylist that is sorted with Collection.sort() calling the ComparTo() included below. CompareTo sorts the file on totalLaps, totalSeconds, and etc.. The question is how do I change the sort criteria later in my process so that the arraylist is sorted on sequence number (the first field and a long number)? The only way I can currently think of doing it is to copy the array and create a separate class file like RaceDetail2 that implements a different CompareTo. To me that seems ridiculous!
    I've self tought myself Java using the online tutorials and a few books so sometimes I find I have some basic gaps in knowledge about the language. What am I missing? Seems like it should be simple.
    private ArrayList detailsArrayList = new ArrayList( );
    // Sort arraylist using compareTo method in RaceDetail file
    Collections.sort(detailsArrayList);
    public class RaceDetail implements Comparable, Cloneable {
         public RaceDetail( long seqNum, String boatNumText, int lapNum, String penalty, String question, long seconds, int totalLaps, long totalSecs, long lastSeqNum, long avg, long interval )
    public int compareTo( Object o )
         RaceDetail rd = (RaceDetail) o;
         int lastCmp = (totalLaps < rd.totalLaps ? -1: (totalLaps == rd.totalLaps ? 0: 1));
         int lastCmpA = boatNumText.compareTo(rd.boatNumText);
         int lastCmpB = (lapNum < rd.lapNum ? -1: (lapNum == rd.lapNum ? 0 : 1 ));
         int lastCmpC = (totalSecs < rd.totalSecs ? -1 : (totalSecs == rd.totalSecs ? 0 : 1 ));
         int lastCmpD = (seqNum < rd.seqNum ? -1 : (seqNum == rd.seqNum ? 0 : 1 ));
         int lastCmpE = (seconds < rd.seconds ? -1 : (seconds == rd.seconds ? 0 : 1 ));
         int lastCmpF = (lastSeqNum < rd.lastSeqNum ? -1 : (lastSeqNum == rd.lastSeqNum ? 0 : 1 ));
         // TotalLaps - Descending, TotalSeconds - ascending, lastSeqNum - ascending
         // Boat - Ascending, Second - ascending, seqNum - ascending
         return (lastCmp !=0 ? -lastCmp :
              (lastCmpC !=0 ? lastCmpC :
                   (lastCmpF !=0 ? lastCmpF :
                        (lastCmpA !=0 ? lastCmpA :
                             (lastCmpE !=0 ? lastCmpE :
                                  lastCmpD)))));
    }

    Thanks talden, adding the comparator below in my main program flow worked and now the arraylist sorts correctly. A couple of additional questions. I tried to place this in my RaceDetail class file and received a compile error so placed it in the main program flow and it worked fine. For organization, I would like to place all my sort routines together. Is there some trick to calling this method if I place it in my RaceDetail? Am I even allowed to do that?
    dhall - just to give you a laugh, this arraylist populates a JTable, uses a TableModel, and the TableSorter from the tutorial. Sorting works great in the JTable. Problem is I have to sort the arraylist a couple of times to calculate some of the fields such as lap times and total laps. I went through the TableSorter 5 or 6 times and never could figure out how to adapt it for what I wanted to do. So here I am using an example in my program and can't interpret it.
    Collections.sort( detailsArrayListLeft, SORT_BY_SEQUENCE );
    static final Comparator SORT_BY_SEQUENCE = new Comparator() {
    public int compare ( Object o1, Object o2 )
         RaceDetail rd1 = (RaceDetail) o1;
         RaceDetail rd2 = (RaceDetail) o2;
         return (rd1.seqNum() < rd2.seqNum() ? -1 : (rd1.seqNum() == rd2.seqNum() ? 0 : 1 ));

  • Formatting a two-dimensional list...

    Is there a way to create a two-dimensional ArrayList of Integers with all cells containing certain values, for example zeros? -I will be storing changing Integer values in certain x- and y-coordinates!!
    Something like:
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();But my problem is that the .get commands cause an Exception if a cell value is not set:
    list.get(x).get(y) and list.get(x).set(y,int)How could I get around the "null" values without Exceptions? Would you first replace the null values with zeros? (Or is there some other way to store such information?)

    If you want to a fill a List up with values, use java.util.Collections.fill().
    But do you really want it full of some kind of value, or do you just want to indicate "no value filled in" for a bunch of positions in the grid? What percentage of positions will not be filled in, or will be filled in with the default?
    Here's a simple sparse grid:
    public class Pair {
      final int x;
      final int y;
      public boolean equals(Object o) {
        Pair p = (Pair) o;
        return p.x == x && p.y == y;
      public int hashcode() {
        return x + y;
    public class SparseGrid {
      private Map<Pair, Integer> grid = new HashMap<Pair, Integer>();
      public Integer get(Pair p) {
        Integer i = grid.get(p);
        if (i == null)
          return 42; // the default.  or just skip this test if you don't want a default
        return i;
      // also a put method, left as exercise
    }That's all untested.

  • How can I Sort Enumeration

    Hi Guys,
    Please help me solving this problem.
    I have some objects which I am read using Enumeration. But these objects are processed without order by Enumeration.
    How can I sort them without looping so they are read in order. Please bear in mind that I can sort them prior to the use of Enumeration.
    Thanks

    Sorry typing mistake 'I can' = 'I cannot'
    and these are custom ObectsThen you must read the objects one by one using the enumeration and put them into a new data structure. This can either be a tree or a list. If it's a tree, like a TreeSet, then the objects will be kept in sorted order as they're entered. If it's a list, like for example an ArrayList, then you'll have to sort it afterwards. Finally you have to iterate one more time using an Iterator but then they'll come out in sorted order.
    For the above to work the class (of the objects you store ) must either implement an interface called Comparable. Alternatively you can supply a so called Comparator object either to the TreeSet constructor or with the ArrayList sort call.

  • JOptionPane troubles

    Hey, I am trying to make a list using JOptionPane so that the user is able to select a string in this list, press ok, and then have that string returned to me. This works fine, and the line of code I've used is....
    removeItem = (String)JOptionPane.showInputDialog(null, "Choose the word you want to remove", "Remove word",
                      JOptionPane.QUESTION_MESSAGE, null, sortedList, "");...the problem is, I have just changed the sortedList input to increase my code efficiency, and now rather than displaying...about 8 list items on screen at one time, it now only displays one. Has anyone got any suggestions on how to increase this?
    Thanks in advance.

    Tom101 wrote:
    I'm having some real trouble trying to replicate this problem. As the program stands at the moment, it reads in a text file and places words into an array list along with an int. The program then copies the strings from the array list into an array, sorts them (using arrays.sort), and then sends them to the output. Now if I enter strings manually to the array it works perfectly. and if I modify my current code so it doesn't include arrays.sort it works perfectly when reading them from a file. Is arrays.sort doing something to it, that triggers JOptionPane to work incorrectly? If you want I can post the method up, however without the rest of the program it wont work the same.Perhaps you could create a new program that goes through the above steps, all of them, and nothing more, and also post the smallest text file to demonstrate the problem. It really should be compilable though, not just a naked method.
    This program could be quite simple. The pseudocode could look something like this:
    begin
       open text file
       read strings into arraylist
       sort arraylist
       convert arraylist to array
       show input dialog and put result into a string
       show string
    endEdited by: petes1234 on Dec 19, 2007 5:57 AM

  • Help on array

    Hi, I want to sort an array which contains Strings (sort according to alphabetical order...)
    after i sort the array...i want to read it at it's original order too...
    that mean's i want to have 2 set of array.....1 with the original order...1 with the sorted order..
    how do i do that?
    let's say i have a container class Club with an array of Names(type String), and a client class...
    with a Club object memberList.how do i do that?
    thank you.

    that mean's i want to have 2 set of array.....1 with
    the original order...1 with the sorted order..OK, how about
      ArrayList origArray = ... whatever ...;
      ArrayList sorted = new ArrayList(origArray);
      Collections.sort(sorted);Now, origArray still has your data in the original order, sorted has it in the sorted order. Note: both are pointing to the same elements.

  • Problem with reading numbers from file into double int array...

    Okay, this is a snippet of my code:
    public void readMap(String file){
            try {
                URL url = getClass().getResource(file);
                System.out.println(url.getPath());
                BufferedReader in = new BufferedReader(new FileReader(url.getPath()));
                String str;
                String[] temp;
                int j=0;
                while ((str = in.readLine()) != null) {
                    temp = str.split(",");
                    for(int i=0;i<temp.length;i++){
                        map[j] = java.lang.Integer.parseInt(temp[i]);
    j++
    in.close();
    } catch (IOException e) {
    System.out.println("Error: "+ e.toString());
    map[][] is a double int array. Now, the code is running through each line of the text file (with each line looking like this: 0,3,6,2,2,3,1,5,2,3,5,2), and I want to put the numbers into a corresponding double int array (which is where map[][] comes in). Now, this code WOULD work, except I need to set the sizes of each array before I start adding, but I don't know how to get the exact sizes.. how can I get around this issue?
    Message was edited by:
    maxfarrar

    You can do a two-dimensional ArrayList? That syntax
    you wrote didn't work.
    I tried doing:
    private ArrayList<ArrayList><Integer>> map;
    Your syntax is just wrong -- or, this forum software has bug in handling angle brackets.
    ArrayList<ArrayList<Integer>>...The closing angle bracket after the second 'ArrayList' is the one generated by the bug. Basically, it should be T<T<T2>> without spaces. Oh, for that matter:
    Arraylist<ArrayList<Integer>>

  • Best efficiently  way to transform a large rows ResultSet to Vector

    Best efficiently way to transform a large rows ResultSet to a 2-dimensional ArrayList or Vector in a minute ?
    If you can help me solve this problem , I 'll give you my duke .

    Why don't you use info objects? For example your table is having col1(number),col2(text/varchar),col3(text/varchar), create an info object like this,
    class MytableInfo implements java.io.Serializable {
    private int col1;
    private String col2;
    private String col3;
    public MytableInfo(int col1,String col2,String col3) {
    this.col1=col1;
    this.col2=col2;
    this.col3=col3;
    public int getCol1() {
    return col1;
    //Getter for other two properties too.
    and in your ResultSet class,
    Vector v = new Vector();
    while(rs.next()) v.add(new MytableInfo(rs.getInt(1),rs.getString(2),rs.getString(3));
    return v;
    So, it will be easier for retrieving the values later and it is a clean way of doing it.
    Sudha

  • Questions on filtering and sorting an arraylist

    Hello All,
    I'm trying to figure out a better way to do this code, but what I'm doing is taking an arrayList and filtering it using iter.remove(), based on a criteria I have, then take the results and sort them. The code below works, but I was seeing class cast exceptions when I tried to do a ss.addAll(list);
    , but it worked when I just added the set object. Why is this and is there a better way to do all this?
    Set set = new HashSet();
    List retList = new ArrayList();
    SortedSet ss = new TreeSet();
    for(Iterator iter = list.iterator(); iter.hasNext();){
    .//More code...
    iter.remove();
    //Remove duplicates.
    set.addAll(list);
    ss.add(set);
    retList.addAll(set);
    return retList;

    Your current code is adding the set (the hash set) as one element (the only element?) of the sorted set. Is this what you want to do? Would you rather add each element of the set to the sorted set?
    I don't know about the class cast exceptions. If you want somebody's comment on this part, you may consider posting code and stack trace.
    I think I'd rely on Collections.sort() for sorting rather than TreeSet. If you prefer TreeSet, why not skip the hash set in between?
    Hope this helps.
    Please remember the code button/tags.

  • Need help Sorting an Arraylist of type Object by Name

    Hey guys this is my first time posting on this forum so hopefully i do it the right way. My problem is that i am having difficulties sorting an Array list of my type object that i created. My class has fields for Name, ID, Hrs and Hrs worked. I need to sort this Array list in descending order according to name. Name is the last name only. I have used a bubble sort like this:
    public static void BubbleSort(TStudent[] x){
    TStudent temp = new TStudent();
            boolean doMore = true;
            while (doMore) {
                doMore = false;
                for (int i=0; i < x.length-1; i++) {
                   if (x.stuGetGPA() < x[i+1].stuGetGPA()) {
    // exchange elements
    temp = x[i]; x[i] = x[i+1];
    x[i+1] = temp;
    doMore = true;
    before many time to sort an array of my class TStudent according to GPA.  This time though i tried using an Array list instead of just a simple array and i can't figure out how i would modify that to perform the same task.  Then i googled it and read about the Collections.sort function.  The only problem there is that i know i have to make my own comparator but i can't figure out how to do that either.  All of the examples of writing a comparator i could find were just using either String's or just simple Arrays of strings.  I couldn't find a good example of using an Array list of an Object.
    Anyways sorry for the long explanation and any help anyone could give me would be greatly appreciated.  Thanks guys
    Edited by: Brian13 on Oct 19, 2007 10:38 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    ok still having problems I have this line of code to try and all Arrays.sort
    Arrays.sort(Employee, TEmployee.FirstNameComparator);Then in my class TEmployee i have
    public static Comparator FirstNameComparator = new Comparator() {
        public int compare(Object employee, Object anotherEmployee) {
          String lastName1 = ((TEmployee) employee).getEmpName().toUpperCase();
          String lastName2 = ((TEmployee) anotherEmployee).getEmpName().toUpperCase();     
           return lastName1.compareTo(lastName2);
      };Here is the rundown of what i have for this. I have 2 classes. One is called TEmployee and that class holds fields for Name, ID, Hrs Worked, Hourly Rate. Then i have another class called myCompany that holds an ArrayList of type TEmployee. Then i have my main program in a Jframe.
    So maybe i am putting them in the wrong spots. The code in TEmployee thats make the comparator is fine. However when i try to call Arrays.sort from class myCompany i get this
    cannot find symbol
    symbol: method sort (java.util.Array list<TEmployee>.java.util.Comparator
    location: class java.util.Arrays
    I have to put the comparator in TEmployee right because thats where my fields for Name are? Do i call the arrays.sort from my main program or do i call that from the class myCompany where my ArrayList of TEmployees are stored?
    Again guys thanks for any help you could give me and if you need any code to see what else is going on just let me know.

  • Can I sort an ArrayList basd on a data member?

    Hello everyone.
    Currently my program stores a lot of objects in an ArrayList.
    Each of these objects has the following data members:
    public class ClassEntity
         //RODM ID VERSION
         private String idClassName;
         private String idFieldName;
         //ENGLISH VERSION
         private String englishClassName;
         private String englishFieldName;
         private String fieldType;
    }I have the following data structure:
    List<ClassEntity> classEntityList = new ArrayList<ClassEntity>();Now is there a way to order the Objects inside the ArrayList so they are in alphabetical order based on the englishFieldName data member?
    I currently iterate through the List and write it to a file and the List is out of order so the writing to file is out of order.
    I saw collections has a .sort() method, but I'm not sure how I would tell the .sort() to sort based on englishFieldName. In C++ I would overload the < operator I'm still new to data structures in Java though.
    Thanks!

    Implement the Comparable Interface in your class, as my example in this posting shows:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=598401

  • Problems with sort, search and write objects o an ArrayList

    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that.
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(
    Any ideas?
    Thank you!
    Anton

    lavalampan wrote:
    Hi
    Lets say that i have two subclasses (the program is not finished so in the end it can be up to 34 classes) of an abstract superclass. I also got one class which basicly is a register in which i've created an ArrayList of the type <abstractClass>. This means that i store the two subclasses in the arrayList. no problems so far i think (at least eclipse doesn't mind).
    1. now, i want to be able to sort the arrayList aswell as search thorugh it. I've tried Collections.sort(arrayList) but it doesn't work. So i have no idea how to solve that. Create a custom comparator.
    >
    2.The search-method i made doesn't work as good as i hoped for either. I ask the user to first decide what to search for (choose subclass) and then input the same properties as the subclass we search for. I create a new object of the subclass with these inputs and try arrayList.contains(subClassObject)
    it runs but it returns +"false"+ even if i create an object with the exact same properties.Implement hashCode and equals.
    >
    3. If i want to write this arrayList to a txtFile so i can import it another time. Which is the best method? first i just thought i'd convert the arrayList to string and then print every single object to a textfile as strings. that worked but i have no good idea how to import that into the same arrayList later. Then i found ObjectOutputStream and import using inputStream.nextObject(). But that doesn't work :(Depends on what your requirement is, but yes, Serialization might work for you. Your classes should in that case implement Serializable.
    Kaj

  • Need help sorting an ArrayList of strings by an in common substring

    I'm trying to sort a .csv file, which I read into an ArrayList as strings. I would like to sort by the IP address within the string. Can someone please help me figure out the best way to sort these strings by a common substring each has, which is an IP address.
    I'm pretty sure that I need to use Collections some how, but I don't know where to begin with them besides trying to look online for help. I had no luck finding any good examples, so I came here as a last resort.
    Thanks for any help provided.

    You need to write your own Comparator class. In the compare() method you substring out the two IP addresses, compare them and return appropriate value. Then you call Collections.sort() and pass your list and comparator.

Maybe you are looking for