Sep 25

## How do I find the largest value in an array?

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

## How do I use Collections.sort() with generics?

```
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>();

Collections.<MyBean>sort(listOfMyBeans);

System.out.println(listOfMyBeans);
}
}
```

written by objects \\ tags: , , , ,

Sep 23

## How do I create a sorted Set?

The TreeSet class maintains its elements in order.

```
Set<String> set = new TreeSet<String>();

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

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

```

written by objects \\ tags: ,