This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
RE: Simple array
Posted by Kishori Sharan on August 01, 2000 at 1:18 PM
Hi You can use the sort method of Arrays class. Arrays.sort ( yourintarray ) ; Here we are using the static method sort of Arrays class whose signature is static void sort ( Object[] a ) ; It sorts the elements in the array and internall it requires that each element of the array must implement Comparable interface. In your case Integer class implements Comparable interface so its compareTo ( ) methos will be used by sort method. After soring you can just read the last element of the array and it will give you the largest value. I have given you an example as follows. /////////////// Example /////////////// import java.util.* ; public class Largest { public Integer getMax ( Integer[] nums ) { Integer maxNum = null ; if ( nums.length > 0 ) { Arrays.sort ( nums ) ; maxNum = nums[nums.length-1] ; } return ( maxNum ) ; } public static void main ( String args[] ) { int i = 0 ; Integer[] nums = { new Integer ( 120 ) , new Integer ( 2 ) , new Integer ( 20 ) , new Integer ( 4 ) } ; Integer maxNum = new Largest().getMax ( nums ) ; i = maxNum.intValue ( ); System.out.println ( "Largest is : " + i ) ; } } Thanx Kishori
Replies:
|