Results 1 to 6 of 6
Thread: Max element in an Array
- 12-02-2007, 09:47 PM #1
Member
- Join Date
- Nov 2007
- Posts
- 70
- Rep Power
- 0
Max element in an Array
I have following array and I want to find the largest value in it. I know I can write a for loop and get the max value. But is there some read made method that Java provides for this very task :confused:
Java Code:int []array = new int[10]; for(int i=0;i<10;i++) array[i] = i;
- 12-03-2007, 01:08 AM #2
Java Code:import java.util.Arrays; ... int[] n = { 3, 7, 4, 6, 5 }; int max = -Integer.MAX_VALUE; for(int j = 0; j < n.length; j++) { if(n[j] > max) max = n[j]; } System.out.println("loop max = " + max); System.out.println("original = " + Arrays.toString(n)); Arrays.sort(n); System.out.println("sorted n = " + Arrays.toString(n)); System.out.println("sorted max = " + n[n.length-1]);
- 12-03-2007, 11:46 AM #3
Senior Member
- Join Date
- Nov 2007
- Posts
- 115
- Rep Power
- 0
Yes, Arrays.sort can serve the purpose. Try it.
- 12-03-2007, 12:11 PM #4
Member
- Join Date
- Nov 2007
- Posts
- 70
- Rep Power
- 0
Thank you all of you.
It work fine.
- 12-03-2007, 12:47 PM #5
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 696
- Rep Power
- 6
You may also use the Collections and Arrays class in-collaboration to get the maximum or the minimum value of an array. The code will be something like:
On the other hand to get the minimum value of an array the code will be:Java Code:Collections.max(Arrays.asList(n));
Java Code:Collections.min(Arrays.asList(n));
Last edited by wsaryada; 12-03-2007 at 12:52 PM.
Website: Learn Java by Examples
- 12-03-2007, 05:26 PM #6
Member
- Join Date
- Nov 2007
- Posts
- 70
- Rep Power
- 0
Similar Threads
-
How to use Idref Element and its advantages
By Java Tip in forum Java TipReplies: 0Last Post: 03-30-2008, 10:04 AM -
Unique element in an array
By revathi17 in forum New To JavaReplies: 2Last Post: 12-31-2007, 08:44 AM -
How to use Idref Element and its advantages
By JavaBean in forum Java TipReplies: 0Last Post: 09-26-2007, 08:37 PM -
a no such element exception
By headlice1 in forum New To JavaReplies: 1Last Post: 08-07-2007, 05:36 PM -
selectSingleNode not returning element...
By schu777 in forum XMLReplies: 4Last Post: 07-31-2007, 05:19 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks