Results 1 to 8 of 8
  1. #1
    jahshuwuh is offline Member
    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    Default Sort ArrayList of different objects

    I'm needing to sort an ArrayList that contains different objects in alphabetical order by different attributes of the different objects. So here is an example I just whipped up to show what I need to do. Say I have two classes, Person, and Animal, and I implement Comparable, override the compareTo so that I'm sorting by the name attribute of Person objects, and species attribute of Animal objects.

    Java Code:
    public class Person implements Comparable{
    
    
    	private String name;
    	private int social;
    	/**
    	 * @return the name
    	 */
    	public String getName() {
    		return name;
    	}
    	/**
    	 * @param name the name to set
    	 */
    	public void setName(String name) {
    		this.name = name;
    	}
    	/**
    	 * @return the social
    	 */
    	public int getSocial() {
    		return social;
    	}
    	/**
    	 * @param social the social to set
    	 */
    	public void setSocial(int social) {
    		this.social = social;
    	}
    	/**
    	 * @param name
    	 * @param social
    	 */
    	public Person(String name, int social) {
    		super();
    		this.name = name;
    		this.social = social;
    	}
    	
    	@Override
    	public String toString() {
    		return "Person [" + (name != null ? "name=" + name + ", " : "")
    				+ "social=" + social + "]";
    	}
    	@Override
    	public int compareTo(Object o)
    	{
    		return this.getName().compareTo(((Person) o).getName());
    	}
    	
    }
    Java Code:
    public class Animal implements Comparable{
    
    	private String species;
    	private int age;
    	
    	
    	/**
    	 * @param species
    	 * @param age
    	 */
    	public Animal(String species, int age) {
    		super();
    		this.species = species;
    		this.age = age;
    	}
    	/**
    	 * @return the species
    	 */
    	public String getSpecies() {
    		return species;
    	}
    	/**
    	 * @param species the species to set
    	 */
    	public void setSpecies(String species) {
    		this.species = species;
    	}
    	/**
    	 * @return the age
    	 */
    	public int getAge() {
    		return age;
    	}
    	/**
    	 * @param age the age to set
    	 */
    	public void setAge(int age) {
    		this.age = age;
    	}
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Animal ["
    				+ (species != null ? "species=" + species + ", " : "") + "age="
    				+ age + "]";
    	}
    
    	public int compareTo(Object o)
    	{
    		return this.getSpecies().compareTo(((Animal) o).getSpecies());
    	}
    }
    Then in my main class I create some objects, add them to the ArrayList, sort them, and print them. But I get a Class Cast Exception, what am I doing wrong? In the actual program I'm working on I have six different classes, so I'm creating six different types of objects, placing them in an arraylist, then I'm wanting to sort them alphabetical by different attributes. So this is just a simpler version of what I'll actually be doing.

    Java Code:
    import java.util.ArrayList;
    import java.util.Collections;
    
    public class Test {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		ArrayList temp = new ArrayList();
    		Person person =  new Person("Josh", 44994);
    		Person person2 = new Person("Shawna", 44556);
    		Animal animal = new Animal ("Gorilla", 23);
    		Animal animal2 = new Animal ("Bird", 12);
    		
    		temp.add(animal);
    		temp.add(animal2);
    		temp.add(person2);
    		temp.add(person);
    		Collections.sort(temp);
    		
    		for (int index = 0; index < 2; index++)
    			System.out.println(temp.get(index));
    	}
    
    }

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default Re: Sort ArrayList of different objects

    Some of the objects in your array are Animals, and some are Persons. The first time an Animal tries to compare itself to a Person or vice versa, its compareTo() method tries to cast the object to the wrong type and blows up.

    In general, you should not be trying to compare two objects of different classes or storing them in the same collection, unless they have a common interface or superclass. And then you would store and compare them as that type.
    Get in the habit of using standard Java naming conventions!

  3. #3
    jahshuwuh is offline Member
    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    Default Re: Sort ArrayList of different objects

    Ah I see. Well, in the actual program I'm doing there is a generic superclass and six classes that extend out from it. So should I just be casting all of the classes to that superclass in the compareTo then?

  4. #4
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default Re: Sort ArrayList of different objects

    You don't need to cast to the superclass. Just make the superclass implement Comparable<YourSuperclass> and give it a method compareTo(YourSuperclass other). Then use an ArrayList<YourSuperclass>.

    If the comparison is based on getName(), then getName() would have to be a method of YourSuperclass. You could make it an abstract method and implement it to return the species of an Animal and the personal name of a Person.

    This slightly rubs me the wrong way because it doesn't accurately model what the classes are supposed to represent. It seems like Person should extend Animal. Both should have a getSpecies() method, but only Person should have a getName() method. (Or if Animal has a getName() method, it should return null unless isPet() returns true. :-P) But that's not a big concern if this is a small educational project.
    Get in the habit of using standard Java naming conventions!

  5. #5
    jahshuwuh is offline Member
    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    Default Re: Sort ArrayList of different objects

    The actual program I'm working on is a Library program that has a superclass Items and subclasses for Books, Magazines, CD's, etc. put all the different objects into an array and then need to print an alphabetical list of all the contents of the library but Books for instance need to be Alphabetical by Author and Magazines by title, so on and so forth. So I have Items (the superclass) as abstract and implements comparable. So I thought all I had to do was override the compareTo in each of the subclasses but that gives the cast exception error, which I see why it does that now. But now what should my compareTo look like then?

  6. #6
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    5

    Default Re: Sort ArrayList of different objects

    If it's really a requirement that subclasses be sortable together, then I'd give their common superclass an abstract method called something like getSortString(). The superclass would implement Comparable<MySuperclass>, and its compareTo() would look something like this:

    Java Code:
    public int compareTo(MySuperclass other) {
        return getSortString().compareTo(other.getSortString());
    }
    Subclasses would implement getSortString(), but they would not override compareTo().
    Get in the habit of using standard Java naming conventions!

  7. #7
    jahshuwuh is offline Member
    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    Default Re: Sort ArrayList of different objects

    Hmm, ok I'll try this. But what would I have in the getSortString() method?

  8. #8
    jahshuwuh is offline Member
    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    Default Re: Sort ArrayList of different objects

    Nevermind, I got it figured out, thanks for your help, your suggestions worked perfectly.

Similar Threads

  1. ArrayList Sort Question
    By kraigballa in forum New To Java
    Replies: 5
    Last Post: 05-04-2012, 03:46 AM
  2. Sort an ArrayList
    By überfuzz in forum New To Java
    Replies: 13
    Last Post: 02-10-2011, 01:18 PM
  3. ArrayList sort
    By Dipke in forum New To Java
    Replies: 1
    Last Post: 08-23-2010, 01:01 PM
  4. how to sort an arraylist?
    By zhangster in forum New To Java
    Replies: 5
    Last Post: 03-19-2010, 08:01 AM
  5. Using Merge Sort to sort an ArrayList of Strings
    By coldfire in forum New To Java
    Replies: 3
    Last Post: 03-13-2009, 01:03 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •