Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
- import java.util.ArrayList;
- import java.util.Collections;
- //Java Sort ArrayList
- public class JavaSortArrayList {
- public static void main(String args){
- //create new ArrayList
- ArrayList<Integer> aListNumbers = new ArrayList<Integer>();
- aListNumbers.add(23);
- aListNumbers.add(11);
- aListNumbers.add(43);
- aListNumbers.add(46);
- aListNumbers.add(98);
- aListNumbers.add(7);
- aListNumbers.add(86);
- System.out.println("ArrayList before sort " + aListNumbers);
- /*
- * To sort ArrayList use,
- * Collections.sort(List list) method.
- */
- Collections.sort(aListNumbers);
- System.out.println("ArrayList after sort" + aListNumbers);
- /*
- * Note: All elements in the ArrayList must implement Comparable interface
- * in order for sort to work. Additionally, none of the elements should throw
- * ClassCastException while being compared with each other.
- *
- * In above example, ArrayList contains all Integer elements, so sort will work
- * by default. If we have an ArrayList which contains objects of custom class,
- * then that class must implement Comparable interface for the sort to work.
- *
- * See the example below.
- */
- //create new ArrayList with custom objects of Class Car.
- ArrayList<Car> aListCars = new ArrayList<Car>();
- aListCars.add(new Car("Merc Benz", 3000000));
- aListCars.add(new Car("Maruti Suzuki 800", 280000));
- aListCars.add(new Car("Honda City", 950000));
- aListCars.add(new Car("Tata Nano", 180000));
- System.out.println("ArrayList before sort " + aListCars);
- //sort ArrayList of Car objects
- Collections.sort(aListCars);
- System.out.println("ArrayList after sort " + aListCars);
- }
- }
- class Car implements Comparable{
- private String name;
- private int price;
- public Car(String name, int price){
- this.name = name;
- this.price = price;
- }
- public String getName(){
- return this.name;
- }
- public int getPrice(){
- return this.price;
- }
- //this method must be defined if we are implementing Comparable interface
- public int compareTo(Object otherCar){
- if(otherCar instanceof Car){
- throw new ClassCastException("Not a valid Car object!!");
- }
- Car tempCar = (Car)otherCar;
- if(this.getPrice() > tempCar.getPrice()){
- return 1;
- }else if(this.getPrice() < tempCar.getPrice()){
- return -1;
- }else{
- return 0;
- }
- }
- }

Dear your sol is the best
Excuse me. I have 2 questions
nice solution
nice solution
good
Thx brother! :) easy solution
I imported into eclipse and
hi why I run it program ,it
Post new comment