Saturday, July 3, 2010

Java Array Examples


1. How to sort integer Array
2. How to sort String Array
3. How to sort Object Array or Array of Objects

1. How to sort integer Array
The out put will be: 1,2,3,4,5,6,7,8,9,10

package basics;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortIntArray();
}

public void sortIntArray() {

int[] intArray = new int[] { 10, 8, 9, 7, 5, 6, 3, 4, 2, 1 };

Arrays.sort(intArray);

for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
System.out.print(",");
}
}
}


2. How to sort String Array
The out put will be: Five,Four,One,Three,Two,

package io;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortStringArray();
}

public void sortStringArray() {

String[] strArray = new String[] { "One", "Two", "Three", "Four",
"Five" };

Arrays.sort(strArray);

for (int i = 0; i < strArray.length; i++) {
System.out.print(strArray[i]);
System.out.print(",");
}
}
}

3. How to sort Object Array or Array of Objects
The out put will be: Chan,Ivan,Sachin,Suresh,

package basics;

import java.util.Arrays;

class ArrayExample {

public static void main(String[] args) {
ArrayExample example = new ArrayExample();
example.sortArray();
}

public void sortArray() {

Person[] array = new Person[] { new Person("Ivan"),
new Person("Suresh"), new Person("Chan"), new Person("Sachin") };

Arrays.sort(array);

for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(",");
}
}

// The Class shoulr implement java.lang.Comparable inteface.
// and should implement compareTo(Object o) method accordingly
class Person implements Comparable {
private String name;

public Person(String name) {
this.name = name;
}

public int compareTo(Object o) {
if (name != null) {
return this.name.compareTo(((Person) o).name);
} else {
return -1;
}
}

public String toString() {
return name;
}
}
}

No comments:

Post a Comment