Sep 25

One solution would be to loop through the array maintaining the largest value found in a variable. Another solution would be to first sort the array, then the largest value would be the last element.


int[] values = { 2, 67, 15, 3, 567 };

// first approach

int largest = values[0];
for (int i=1; i<values.length; i++)
{
   smallest = Math.max(smallest, values[i]);
}

// second approach

java.util.Arrays.sort(values);
largest = values[lalues.length-1]; 

written by objects \\ tags: ,

Sep 25

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyBean implements Comparable<MyBean>
{
   private int value;

   public MyBean()
   {
   }

   public MyBean(int value)
   {
      setValue(value);
   }

   public int getValue()
   {
      return value;
   }

   public void setValue(int value)
   {
      this.value = value;
   }

   public int compareTo(MyBean other)
   {
       return value - other.value;
   }

   public String toString()
   {
	   return Integer.toString(value);
   }
   
   public static void main(String[] args)
   {
      List<MyBean> listOfMyBeans = new ArrayList<MyBean>();
      listOfMyBeans.add(new MyBean(5));
      listOfMyBeans.add(new MyBean(1));
      listOfMyBeans.add(new MyBean(4));

      Collections.<MyBean>sort(listOfMyBeans);

      System.out.println(listOfMyBeans);
   }
} 

written by objects \\ tags: , , , ,

Sep 23

The TreeSet class maintains its elements in order.


Set<String> set = new TreeSet<String>();
set.add("one");
set.add("two");
set.add("three");

for (String s : set)
{
   System.out.println(s);
}

// Output will be (as String's are sorted alpabetically):
// one
// three
// two 

written by objects \\ tags: ,