Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Random;
- class Test {
- public static void main(String args[]) {
- ArrayList<Employee> list = new ArrayList<>(); // make an empty list
- Random rn = new Random(); // random number generator
- // put 20 objects into list with random values
- for (int i = 0; i < 20; i++) {
- list.add(new Employee(rn.nextInt(100), rn.nextInt(100)));
- }
- // do a very simple bubble sort. Very inefficient but who cares
- for (int i = 0; i < list.size(); i++) {
- for (int j = 0; j < list.size() - 1; j++) {
- if (list.get(j).ID < list.get(j + 1).ID) { // sort on ID field
- Employee temp = list.get(j).copy(); // swap j and j+1
- list.set(j, list.get(j + 1));
- list.set(j + 1, temp);
- }
- }
- }
- // see what we've got
- for (int i = 0; i < list.size(); i++) {
- System.out.println(list.get(i));
- }
- }
- }
- class Employee {
- int ID, data;
- Employee(int ID, int data) {
- this.ID = ID;
- this.data = data;
- }
- Employee copy() {
- return new Employee(ID, data);
- }
- public String toString() {
- return ID + " : " + data;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment