Sorting a list of different class objects

Hi All ,
How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .
Thanks ,
Rajesh Reddy

rajeshreddyk wrote:
Hi All ,
How to sort a List a.which contains objects of different Classes, b. objects of same class . Is it possible to sort these by implementing Comparable interface .Well, if objects of different classes are kept in the same List and you want to sort them together they at least have that in common. They're Comparable-able. -:) To manifest that the different classes could all implement a Comparableable interface (or maybe Intercomparable would be a better choise of name.)

Similar Messages

  • While running my app I get the below error  - have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature

    I am running ATG[10.1.2] app on Jboss [EAP 5.1.0 GA] I am able to open dyn/admin however when I start my app I get the below error
    java.lang.LinkageError: loader constraint violation: when resolving method "atg.servlet.ServletUtil.setSessionConfNumCacheRequest(Ljavax/servlet/http/HttpServletRequest;)Ljavax/servlet/http/HttpServletRequest;" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, atg/filter/dspjsp/PageFilter, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for resolved class, atg/servlet/ServletUtil, have different Class objects for the type javax/servlet/http/HttpServletRequest used in the signature
      at atg.filter.dspjsp.PageFilter.doFilter(PageFilter.java:215)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ForwardFilter.doFilter(ForwardFilter.java:263)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at atg.servlet.ErrorFilter.doFilter(ErrorFilter.java:279)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:638)
      at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:446)
      at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
      at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:310)
      at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:416)
      at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
      at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:286)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
      at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
      at java.lang.Thread.run(Thread.java:680)
    11:22:47,413 ERROR [[localhost]] Exception Processing ErrorPage[errorCode=500, location=/global/errorPage500.jsp]

    The supported JBoss version for 10.1.2 is JBoss EAP 5.1.2 but I don't think that your issue is caused because of this. Your issue is more of an environmental thing as you are probably getting two different versions getting loaded of class javax.servlet.http.HttpServletRequest and so correspondingly two different Class objects as the error shows. One reason for this could be if you include any server-specific libraries (in present case the Servlet API JAR which contains the class javax.servlet.http.HttpServletRequest) of a different version in the /WEB-INF/lib of your web application. Try removing it from there if so and see if that helps.

  • Sorting a list with parent/child object relations

    Hi,
    I have an ArrayList of Genre objects that I want to sort:
    class Genre{
    int CategoryID;
    int ParentCategoryID;
    String name;
    String level;
    Example objects:
    Pop (CategoryID=10, ParentCategoryID=root, "popular music", 1);
    Jazz (CategoryID=11, ParentCategoryID=root, "jazz music", 1);
    Indie pop (CategoryID=12, ParentCategoryID=10, "indie pop", 2);
    American Indie pop (CategoryID=13, ParentCategoryID=12, "american indie pop", 3);
    Soul (CategoryID=15, ParentCategoryID=root, "soul music", 1);
    Commercial pop (CategoryID=14, ParentCategoryID=10, "commercial pop", 2);
    I hope that you see the point:
    I want that the order will be like this in my arraylist:
    jazz music
    popular music
    commercial pop
    indie pop music
    american indie pop
    soul music
    I'll implement the comparator-class in Genre and then add the compareTo-method in my genre-class.
    But my brain is too tired to figure out what to write in the compareTo-method?
    Have somebody done a similar method??
    Best regards,
    Thomas

    Unfortunately is this solution not plausible since I
    don't can have the parent genre in the genre class.
    ... Hashmap?Hashmap works. Here you go, using your structure, minus the level, I'm sure you can work around that though. Don't use -1 as a category id, it's reserved for your root. This code is not thread safe, I leave that to you. Don't forget that as implemented, parent Genres must be constructed prior to any of their children. You could get around this with a two pass initialization process.
    // Not thread safe.
    import java.util.*;
    public class Genre implements Comparable {
         private static Map<Integer, Genre> genreForId = new HashMap<Integer, Genre>();
         private int id;
         private int level;
         private int parentId;
         private String name;
         public Genre(int id, int parentId, String name) {
              this.id = id;
              this.parentId = parentId;
              this.name = name;
              this.level = level(this);
              Genre.genreForId.put(id, this);
         private static int level(Genre genre) {
              int i = 0;
              while (genre != null) {
                   genre = genre.getParent();
                   i++;
              return i;
         public static void main(String[] args) {
              Genre pop = new Genre(10, -1, "popular music");
              Genre jazz = new Genre(11, -1, "jazz music");
              Genre indiePop = new Genre(12, 10, "indie pop");
              Genre americanIndiePop = new Genre(13, 12, "american indie pop");
              Genre soul = new Genre(15, -1, "soul music");
              Genre commercialPop = new Genre(14, 10, "commercial pop");
              Genre[] genres = { pop, jazz, indiePop, americanIndiePop, soul,
                        commercialPop };
              Arrays.sort(genres);
              System.out.println(Arrays.toString(genres));
         public int compareTo(Object o) {
              Genre lhs = this;
              Genre rhs = (Genre) o;
              switch (Integer.signum(lhs.getLevel() - rhs.getLevel())) {
              case -1:
                   rhs = rhs.getParent();
                   if (lhs == rhs)
                        return -1;
                   break;
              case 0:
                   if (lhs == rhs)
                        return 0;
                   else {
                        if (lhs.getParent() == rhs.getParent())
                             return lhs.getName().compareTo(rhs.getName());
                        else {
                             lhs = lhs.getParent();
                             rhs = rhs.getParent();
                   break;
              case 1:
                   lhs = lhs.getParent();
                   if (lhs == rhs)
                        return 1;
              return lhs.compareTo(rhs);
         public int getLevel() {
              return level;
         public String getName() {
              return name;
         public Genre getParent() {
              return Genre.genreForId.get(getParentId());
         public int getParentId() {
              return parentId;
         public String toString() {
              return name;
    }-S

  • New class object statically.

    I have a class Test. This class has a static method which has as its purpose to create a new Test object. I currently have something like this:
    public static Test getInstance() {
      return new Test();
    }I was wondering if it is possible to write this code in such a way that no explicit reference to Test was made... and, as the always important follow up question, if it is possible, whether it is wise to do so?

    I have an interface and several classes implementing
    that interface. Each of these classes has a static
    method that has a Hashtable as a parameter. When that
    static method is called, the method creates an object
    of the class it is in and then adds the object to the
    Hashtable (the key for this entry is retrieved from
    the class its from).
    The 'problem' is that I have to write each of those
    methods in each class myself, when all I really want
    is to do the exact same thing over and over again
    (with each of the classes), just with different class
    objects.it's not "the same exact thing" over and over, though, is it? you're instantiating different classes in different methods. are you doing this to keep track of instances? you could have a factory that uses reflection to instantiate classes, and add them to the correct Map, but it can be awkward

  • LINQ sorting on List Object - Various Object Type

    I try to sort a List<Object> where the Object are different classes but all share the same Property Name for instance.
    I got a Base Class where Class A and Class B inherit from the Base Class.
    So during the Linq query I cannot specify with object type this is.
    Problem here "from ?????Entry_Global?????? list in Entries"
    Thanks for helping.
    ////Entries is a List<Object> which consist of class object as following\\\\\
    public abstract class EntryBase<T>
    private string _Name;
    public string Name
    get { return this._Name; }
    set { this.SetProperty(ref this._Name, value); }
    public class Entry_Global : EntryBase<Entry_Global>
    public class Entry_CC : EntryBase<Entry_CC>
    private string _url; //Web url
    public string Url
    get { return this._url; }
    set { this.SetProperty(ref this._url, value.Contains("http") ? value : "http://" + value); }
    public List<Object> SortBy()
    IEnumerable<KeyedList<string, object>> groupedEntryList = null;
    //The proble reside in the fact that list is not only one type
    //so when comes in the orderby "Name" it doesn't know Name
    //or any other properties which are all common to all those class
    //It does not want to convert Entry_CC or Entry_Global to EntryBase
    groupedEntryList =
    from ?????Entry_Global?????? list in Entries
    orderby list.Name
    orderby list.CategoryRef.Name
    group list by list.CategoryRef.Name into listByGroup
    select new KeyedList<string, object>(listByGroup);
    return groupedEntryList.ToList<object>();

    Entry_Global and Entry_CC don't share the same base class since EntryBase<Entry_Global> and EntryBase<Entry_CC> are two totally different types so you cannot cast the objects in the List<object> to a common base class in this case.
    You could cast from object to dynamic though:
    public List<Object> SortBy()
    List<object> objects = new List<object>();
    objects.Add(new Entry_Global { Name = "K" });
    objects.Add(new Entry_CC { Name = "A" });
    objects.Add(new Entry_Global { Name = "I" });
    objects.Add(new Entry_CC { Name = "C" });
    var sortedObjectsByName = (from o in objects
    let t = (dynamic)o
    orderby t.Name
    select o).ToList();
    return sortedObjectsByName;
    The dynamic keyword makes a type bypass static type checking at compile-time:
    https://msdn.microsoft.com/en-us/library/dd264736.aspx. This basically means that a dynamic type is considered to have any property of any name at compile time. Of course you will get an exception at runtime if the type doesn't have a Name property but
    providied that all objects in the List<T> to be sorted are of type EntryBase<T> you will be safe as long as the EntryBase<T> type defines the Name property that you sort by.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • Two equal objects, but different classes?

    When programming on binding Referenceable object with JDK version 1.5.0_06, I have encountered a very strange phenomenon: two objects are equal, but they belong to different classes!!!
    The source codes of the program bind_ref.java are listed as below:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import javax.naming.*;
    import javax.naming.spi.ObjectFactory;
    import java.util.Hashtable;
    public class bind_ref {
    public static void main( String[] args ) {
    // Set up environment for creating the initial context
    Hashtable env = new Hashtable();
    env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
    env.put( Context.PROVIDER_URL, "file:/daniel/" );
    Context ctx = null;
    File f = null;
    Fruit fruit1 = null, fruit2 = null;
    byte [] b = new byte[10];
    try {
    ctx = new InitialContext( env );
    Hashtable the_env = ctx.getEnvironment();
    Object [] keys = the_env.keySet().toArray();
    int key_sz = keys.length;
    fruit1 = new Fruit( "Orange" );
         SubReference ref1 = fruit1.getReference();
    ctx.rebind( "reference", fruit1 );
         fruit2 = ( Fruit )ctx.lookup( "reference" );
         System.out.println( "ref1's class = (" + ref1.getClass().toString() + ")" );
         System.out.println( "fruit2.myRef's class = (" + fruit2.myRef.getClass().toString() + ")" );
         System.out.println( "( ref1 instanceof SubReference ) = " + ( ref1 instanceof SubReference ) );
         System.out.println( "( fruit2.myRef instanceof SubReference ) = " + ( fruit2.myRef instanceof SubReference ) );
         System.out.println( "ref1.hashCode = " + ref1.hashCode() + ", fruit2.myRef.hashCode = " + fruit2.myRef.hashCode() );
         System.out.println( "ref1.equals( fruit2.myRef ) = " + ref1.equals( fruit2.myRef ) );
    } catch( Exception ne ) {
    System.err.println( "Exception: " + ne.toString() );
    System.exit( -1 );
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++
    All the outputs are shown as below:
    =======================================================
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    SubReference: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    --------- (i)subref.hashCode() = (-1759114666)
    FruitFactory: obj's class = (class javax.naming.Reference)
    FruitFactory: obj's hashCode = -1759114666
    FruitFactory: obj = (Reference Class Name: Fruit
    Type: fruit
    Content: Orange
    FruitFactory: ( obj instanceof SubReference ) = false
    FruitFactory: subref_class_name = (Fruit)
    Fruit: I am created at Mon Jun 18 11:35:13 GMT+08:00 2007
    ref1's class = (class SubReference)
    fruit2.myRef's class = (class javax.naming.Reference)
    ( ref1 instanceof SubReference ) = true
    ( fruit2.myRef instanceof SubReference ) = false
    ref1.hashCode = -1759114666, fruit2.myRef.hashCode = -1759114666
    ref1.equals( fruit2.myRef ) = true
    ========================================================
    I hightlight the critical codes and outputs related to the strangeness with bold texts.
    Who can tell me what happens? Is it really possible that two objects belonging to different classes are equal? If so, why that?

    It can also depend on how you implement the equals method.
    class Cat {
        String name;
        Cat(String n) {
            name = n;
    class Dog {
        String name;
        Dog(String n) {
            name = n;
        public boolean equals(Object o) {
            return name.equals(o.name);
        public static void main(String[] args) {
            Dog d = new Dog("Fred");
            Cat c = new Cat("Fred");
            System.out.println(d.equals(c));
    }

  • Problem - different classes in a custom list

    Hi,
    Im making a school project and must use this List-class, written by some of our teachers.
    The problem is, the nodes in the list are type of Objects, and i must store multiple types of classes in the list.
    Storing works fine, but when i want to do something with a specific item in the list, i cannot use it's methods since its now type Object. So everytime I want to use it, i have to cast the Object back to the class it was originally, and there are like 20 of them so thats hell of a lot if-clauses to check which type must i cast it to, and thats in every place that does something with the list.
    Am I being extremely dumb here? Whats the proper way to do this?

    ju551 wrote:
    All the objects are kind of creatures that are inherited from the same abstract class.
    Hmm did i get this right now... So if i make that ancestor class into an interface, I can just cast them everytime to that class and when i call its (abstract) methods it will invoke the real methods in the subclasses?Ah, you don't need an interface in that case. You can just cast all instances to the base class and call the methods that are available there. The methods in the subclasses will be called if they are overridden.
    Kaj

  • When it's required to share a single object in different classes????

    Hi friends...
    I am new to java programming language....
    when it is required to share a single object in different classes???
    and
    please give me one example with explanation...
    Thank you
    regards Shree

    sun_shree wrote:
    Thanks for all giving reply.....
    please write the constructor which is accepting reference and please,,,,,, explain......
    Thanking youNo.
    This will be covered in any Java textbook or tutorial. Like this one: [http://java.sun.com/docs/books/tutorial/java/javaOO/arguments.html]
    After reading it and writing some code of your own to test your understanding, if you still have a specific question, post again.

  • Save tree the lists of which is class' object

    Hi, my question :
    how can i save tree the lists of which is class' object?
    i save tree with the help of ObjectOutputStream class, but when i read tree object from file i have leaf without name(clean leaf)
    how read and save tree in file for normal with it?
    Code of my function for save tree:
    import javax.swing.JTree;
    import java.io.*;
    import java.util.*;
    public class SaveTree {
        public SaveTree(){
        public void saveTree(JTree tree){
            try{
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tree.info"));
            out.writeObject(tree);
            out.close();
            catch(Exception e){
                e.printStackTrace();
        public JTree loadTree(){
            JTree tree = new JTree();
            try{
                ObjectInputStream in = new ObjectInputStream(new FileInputStream("tree.info"));
                tree = (JTree)in.readObject();
                in.close();
            catch(Exception e){
                e.printStackTrace();
            return tree;
    }the code where i create new node as class' object
    public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if (ADD_COMMAND.equals(command)) {
                //Add button clicked
                book = new DefaultMutableTreeNode(new BookInfo
                (name.getText(),
                "file:///"+ System.getProperty("user.dir") + "/" + ID.getText() + ".html", Integer.parseInt(ID.getText())));           
                treePanel.addObject(book);
                name.setText("");
                ID.setText("");
    }my class BookInfo
    public class BookInfo {
            public String bookName;
            public String bookURL;
            private int bookID;
            public BookInfo(String book, String filename, int ID) {
                bookID = ID;
                bookName = book;
                bookURL = filename;
                System.out.println(bookURL);
                if (bookURL == null) {
                    System.err.println("Couldn't find file: "
                                       + filename);
            public String toString() {
                return bookName;
            public int getID(){
                return bookID;
            public void setID(int ID){
                bookID = ID;
        }thanks for attention ! :)

    Jos, thanks for answer :)
    Erm, get the TreeModel from the JTree, serialize it and later deserialize it and set it as the TreeModel for your JTree again?
    kind regards,
    JosHm, i save treeModel the same way, but when i (de)serialize treeModel from file i get clean tree
    my function to save treeModel
    class Save{
    public Save(){}
    public DefaultTreeModel loadModel(DefaultTreeModel model){
            try{
                ObjectInputStream in = new ObjectInputStream(new FileInputStream("tree.info"));
                model = (DefaultTreeModel)in.readObject();
                in.close();
            catch(Exception e){
                e.printStackTrace();
            return model;
            public DefaultTreeModel saveModel(DefaultTreeModel model){
            try{
                ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tree.info"));
                out.writeObject(model);
                out.close();
            catch(Exception e){
                e.printStackTrace();
            //return model;
    }and here i init tree with treeModel
    Save save = new Save();
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(myObject);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(save.saveModel(model));
    JPanel panel  = new JPanel();
    panel.add(new JScrollPane(tree));
    this.add(panel);Edited by: Tmrs on May 18, 2008 6:00 AM

  • How to access form objects from different class?

    Hello, I am new to java and i started with netbeans 6 beta,
    when i create java form application from template i get 2 classes one ends with APP and one with VIEW,
    i put for example jTextField1 with the form designer to the form and i can manipulate it's contents easily from within it's class (let's say it is MyAppView).
    Question>
    How can i access jTextField1 value from different class that i created in the same project?
    please help. and sorry for such newbie question.
    Thanks Mike

    hmm now it says
    non static variable jTree1 can not be referenced from static context
    My code in ClasWithFormObjects is
    public static void setTreeModel (DefaultMutableTreeNode treemodel){
    jTree1.setModel(new DefaultTreeModel(treemodel));
    and in Class2 it is
    ClasWithFormObjects.setTreeModel(model);

  • Putting a Class Object into a Vector

    HI all
    I need to put a class object into another classes vector, then be able to read it and retrieve data.
    I can put the object into the vector but all i seem to be able to retrieve is data like Account@2343c2.
    Is this some sort of tag? How do i get to the data?
    thankz
    joey

    That's what you get when you print an object which does not have its own toString() method to do anything different - it picks up the Object class's toString method instead. For example:
    System.out.println(new Object());It sounds like you're doing something like this:
    Vector v = new Vector();
    v.add(new Account(42));If you were to do the following, you would see that sort of output:
    System.out.println(v.get(0));The appropriate way to do this would be something like the following:
       // Use a List reference instead of a Vector reference, and create
       // an ArrayList object in preference to a Vector object
       List list = new ArrayList();
       list.add(new Account(42));
       // Iterate through the list of accounts - use an
       // iterator because this prevents off-by-one errors
       // that arise with direct indexing.
       Iterator i = list.iterator();
       while(i.hasNext()) {
          // Cast the reference returned by the iterator from
          // Object to Account so that we can call account-specific
          // methods.
          Account current = (Account)i.next();
          // Call the method specific to the Account class (getBalance
          // is just an example that I made up).
          System.out.println(current.getBalance());
       }

  • Sort array list and using comparable

    With the following code I would like to setup a score object for the current player.
    Change it to a string(Is it correct to say parse it to a string type)
    Then add it to the arraylist.
    So I can sort the array list according to the string size.
    That's why I have the variables in that order.
    So if 3 players have the same amount of guesses, they can be positioned on the high score list according to their gameTime.
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);So the error message says " The method add(Score) in the type arrayList <Score> is not applicable for the arguments(string)"
    Now, I understand that, I would like to know if there is another way to achieve what I am trying to do.
    Is the string idea I am trying here possible? is it practical or should I use comparable?
    I have looked at comparable, but I don't get it.
    Will my Score class implement comparable. I am looking at an example with the following code.
    Employee.java
    public class Employee implements Comparable {
        int EmpID;
        String Ename;
        double Sal;
        static int i;
        public Employee() {
            EmpID = i++;
            Ename = "dont know";
            Sal = 0.0;
        public Employee(String ename, double sal) {
            EmpID = i++;
            Ename = ename;
            Sal = sal;
        public String toString() {
            return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
        public int compareTo(Object o1) {
            if (this.Sal == ((Employee) o1).Sal)
                return 0;
            else if ((this.Sal) > ((Employee) o1).Sal)
                return 1;
            else
                return -1;
    ComparableDemo.java
    import java.util.*;
    public class ComparableDemo{
        public static void main(String[] args) {
            List ts1 = new ArrayList();
            ts1.add(new Employee ("Tom",40000.00));
            ts1.add(new Employee ("Harry",20000.00));
            ts1.add(new Employee ("Maggie",50000.00));
            ts1.add(new Employee ("Chris",70000.00));
            Collections.sort(ts1);
            Iterator itr = ts1.iterator();
            while(itr.hasNext()){
                Object element = itr.next();
                System.out.println(element + "\n");
    }The thing I don't understand is why it returns 0, 1 or -1(does it have to do with the positioning according to the object is being compared with?)
    What if I only use currentScore in a loop which loops every time the player restarts?
    //create score object
                   Score currentScore = new Score(guessCount, gameTime, name);
                   String currentScoreToString = currentScore.toString();
                   //add score to arrayList
                   scores.add(currentScoreToString);Also why there is a method compareTo, and where is it used?
    Thanks in advance.
    Edited by: Implode on Oct 7, 2009 9:27 AM
    Edited by: Implode on Oct 7, 2009 9:28 AM

    jverd wrote:
    Implode wrote:
    I have to hand in an assignment by Friday, and all I have to do still is write a method to sort the array list. Okay, if you have to write your own sort method, then the links I provided may not be that useful. They show you how to use the sort methods provided by the core API. You COULD still implement Comparable or Comparator. It would just be your sort routine calling it rather than the built-in ones.
    You have two main tasks: 1) Write a method that determines which of a pair of items is "less than" the other, and 2) Figure out a procedure for sorting a list of items.
    The basic idea is this: When you sort, you compare pairs of items, and swap them if they're out of order. The two main parts of sorting are: 1) The rules for determining which item is "less than" another and 2) Determining which pairs of items to compare. When you implement Comparable or create a Comparator, you're doing #1--defining the rules for what makes one object of your class "less than" another. Collections.sort() and other methods in the core API will call your compare() or compareTo() method on pairs of objects to produce a sorted list.
    For instance, if you have a PersonName class that consists of firstName and lastName, then your rules might be, "Compare last names. If they're different, then whichever lastName is less indicates which PersonName object is less. If they're the same, then compare firstNames." This is exactly what we do in many real-life situations. And of course the "compare lastName" and "compare firstName" steps have their own rules, which are implemented by String's compareTo method, and which basically say, "compare char by char until there's a difference or one string runs out of chars."
    Completely independent of the rules for comparing two items is the algorithm for which items get compared and possibly swapped. So, if you have 10 Whatsits (W1 through W10) in a row, and you're asked to sort them, you might do something like this:
    Compare the current W1 to each of W2 through W10 (call the current one being compared Wn). If any of them are less than W1, swap that Wn with W1 and continue on, comparing the new W1 to W(n+1) (that is, swap them, and then compare the new first item to the next one after where you just swapped.)
    Once we reach the end of the list, the item in position 1 is the "smallest".
    Now repeat the process, comparing W2 to W3 through W10, then W3 to W4 through W10, etc. After N steps, the first N positions have the correct Whatsit.
    Do you see how the comparison rules are totally independent of the algorithm we use to determine which items to compare? You can define one set of comparison rules ("which item is less?") for Whatsits, another for Strings, another for Integers, and use the same sorting algorithm on any of those types of items, as long as you use the appropriate comparison rules.Thanks ;)
    massive help
    I understand that now, but I am clueless on how to implement it.
    Edited by: Implode on Oct 7, 2009 10:56 AM

  • How to get a LabVIEW class object to expose an invoke-node method?

    Hi,
          I like the property/invoke-node "paradigm" used for interacting with "objects".  Can LabVIEW-class objects expose their properties and methods this way?  Can one or more LabVIEW-class objects be compiled into a library or "assembly" (or other distrubution format) that allows the property/invoke-node usage?
    I've looked at (but not completely understood) "Creating LabVIEW Classes".  Have also searched for related posts.
    The pic below shows an invoke node wired to a class with a Public VI "VAT.Status.Hello.vi".  I'd like to see VAT.Status.Hello show-up as a Method.  (I just tried "Select Method", and selected "VAT.Status.Hello.vi" but dialog's "OK" button stays greyed-out.)
    Cheers.
    Message Edited by tbd on 03-29-2007 03:15 PM
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)
    Attachments:
    VATStat.JPG ‏54 KB

    Hi Aristos,
          Thanks for the reply!  It was a bit dissappointing, though.
    It appears the LabVIEW-class object will be moving away from (what seems to me) a convenient object-interface presented by the invoke-node/method paradigm - which allows us to interface with a large set of "objects" (.NET, ActiveX, LabVIEW GUI, VISA Resource, ?) in a similar manner and independent of the object's origin.  Being able to read the methods and parameters that appear in these nodes is also helpful for understanding diagram logic!
    I do like the option of dropping a friendly "VI looking" icon on the diagram, but perhaps an optional - even default - VI-icon representation for a class-object invoke-node is feasible - so the LabVIEW class-object could be the more generic object first, but with a traditional-G representation(?)
    Given the answer "We would like, someday, to support the property node"
    and "in the next version of LV, wiring the LV class to the property/invoke nodes will break the wire so we'll avoid confusion in the future",
    ... I guess you'll break the wire in the next version, but (perhaps) allow it again - if support of the property node is ever implemented?
    Regards.
    P.S. For the record, huge THANKS to whoever it was that straightened-out enumerated-types (somewhere) between LV4.1 and LV6.1.  Every time I add or remove an enumeration in a typedef, I silently give thanks to the bright and thoughtful soul(s) who made this valuable tool work so well!
    Hello. This is your friendly neighborhood R&D guy for LabVIEW classes.
    Regarding your request about property and invoke nodes as relates to LV classes....
    Short story: We would like, someday, to support the property node. We have no intention of ever supporting the invoke node.
    Long story: As we were creating LV classes, we had to evaluate the right programming interface for these things. We wanted LV classes to behave as new data types in LV. A developer should be able to create a LV class, then give it to someone who doesn't even know OO programming, and that second programmer could use the new data type without learning a lot of new concepts. From this principle, we held fast to the idea that the programming interface should be subVI calls whereever possible. The invoke node is really nothing more than a VI minus the icon. If you want, you can popup on any subvi node and uncheck the option "View as Icon". This will make the node display in a way that has the terminals listed as text, like the invoke node. So, at the end of the day, the invoke node is simply a subroutine call in LV that is language dependent, as opposed to the language independent iconography of LV generally.
    The property node is a slightly different story -- the functionality of a property node is actually different than an invoke node as its terminals are various subsets of the properties available, not a fixed list of parameters like the invoke node. The property node provides a nice interface for setting multiple properties in a block and only having to check a single error return. Very friendly. Our intent is to allow you to create a VI that has 5 terminals: object in, object out, error in, error out, and either a single input or a single output of your chosen type. VIs with this conpane could be marked as "properties" of the class and would show up when you wire the class wire to the property node. We would call the subVIs behind the scenes as needed to get/set the properties.
    This is on the longer term roadmap because it is "syntactic sugar" -- it sweetens the programming style, but it is not necessary to program effectively. You can get the same effect by writing those same VIs and stringing them along on a block diagram "railroad track" style. We'll probably get around to it in three or four versions of LV -- there are some major user requests that impact functionality that have to get done first.
    PS -- in the next version of LV, wiring the LV class to the property/invoke nodes will break the wire so we'll avoid confusion in the future of people thinking there's a way to use these nodes.
    Message Edited by Aristos Queue on 04-02-2007 09:56 AM
    Message Edited by tbd on 04-03-2007 12:39 PM
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • Sort(java.util.LinkedList java.lang.Object ) doesn't work

    Why doesn't this work?
    LinkedList<Object> sysPropsKeys = new LinkedList<Object>(System.getProperties().keySet());
    Collections.sort(sysPropsKeys);
    cannot fnd symbol
    symbol : method sort(java.util.LinkedList<java.lang.Object>)
    location: class java.util.Collections

    I will admit to not having Java1.5 installed on my machine. Haven't yet had the chance to play with generics, but the above DOES work in 1.4, and SHOULD work in 1.5
    Maybe I'm naive but, System.getProperties() returns a Properties object right?
    According to the API: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html: Each key and its corresponding value in the property list is a string.
    All the keys SHOULD be strings.
    AFAIK string are comparable, and shouldn't throw class cast exceptions
    Thus the keys returned from getProperties SHOULD be comparable, and compatible for comparision.
    Ok, I can see your point in that some hackers abuse the Properties class by putting non string keys/values into the Properties Map. In that case the code would become more like your above. I'd probably still go with a TreeMap though, rather than a sorted list of keys. Most time you want the keys, you want the values as well. So if the intention is to print out a sorted list of system properties, and their values, keeping it in a map is best.
    Just my 2 cents,
    evnafets

  • Sort Xml list

    Hello,
    I am trying to learn actionscript 3 for work and have a very
    specific project I need it for. I have been searching every
    available tutorial have bought a few books to read but I cannot
    find out how to do a few simple things.
    The main thing I need to do right now is sort an xml list by
    the date of an event before I start picking which nodes to display.
    (<dt_event_start>) I need the function to be able to sort by
    date or by alpha for a different xml list I will be sorting later,
    not both at the same time, just one or the other. My code is sparse
    right now, all it does is pick events in a certain city and write
    them all in one big list to a text box on screen. Later I will have
    to separate out each part to make a header for each event and
    choose which nodes to display, so i need to sort the xml list
    before I start displaying the nodes in separate text boxes within a
    larger container repeated with a loop through the list.
    included is one xml entry and the as3 code i have so far
    Any help would be greatly appreciated and then I can go
    looking for the other code I need.

    This thread was "imported" from the old forums -- most, if not all, code seems to have disappeared. But here are the sort functions I posted:
    function sortXML(source:XML, elementName:Object, fieldName:Object,
    options:Object = null):XML
         // list of elements we're going to sort
         var list:XMLList=source.elements("*").(name()==elementName);
         // list of elements not included in the sort -
         // we place these back into the source node at the end
         var excludeList:XMLList=source.elements("*").(name()!=elementName);
         list= sortXMLList(list,fieldName,options);
         list += excludeList;
         source.setChildren(list);
         return source;
    function sortXMLList(list:XMLList, fieldName:Object, options:Object =
    null):XMLList
         var arr:Array = new Array();
         var ch:XML;
         for each(ch in list)
               arr.push(ch);
         var resultArr:Array = fieldName==null ?
               options==null ? arr.sort() :arr.sort(options)
               : arr.sortOn(fieldName, options);
         var result:XMLList = new XMLList();
         for(var i:int=0; i<resultArr.length; i++)
               result += resultArr[i];
         return result;

Maybe you are looking for

  • Form inside Form

    Hi everybody, How can I view a form inside a form? i.e. To have the upper part of the form to display another form as a header. Thanks in advance ;)

  • Degenerate Dimension

    While performing modeling in BMM layer I am hitting an issue. I have two fact tables Revenue and Charges. Both has Sales Order Number as common column (Sales Order Number) is available in both the fact tables. Now I want to create a report across bot

  • Fireox 3.6.8 does not open

    with earlier version like 3.5, I didn't have any problem with 3.6.8 I cannot open Firefox unless with ''ouvrir sans échec ?

  • How to add left and right margins in Topic?

    Hi I am using RH10, as part of TCS4. I am creating screen layouts by just modifying the existing ones. I noticed that there is no margin/ space between the topic border and the topic content in it. When I searched for that in mobile.css, I did not fi

  • "dynamiclinkmanager quit unexpectedly" - persistant dialogue

    Has anyone else had this problem with Photoshop CC and Lightroom CC?  The dialogue seems to be triggered by attempting to open a file.  It repeats and makes using the software impossible.  This has been happening to me for a few weeks now - very frus