Core java - Advance Topics
  • Welcome
  • Schedule
  • 1) Exception Handling
    • 1) Introduction to Exception Handling
    • 2) Categories of Exceptions
    • 3) Creating a method that throws an exception
    • 4) Creating Custom Exception Classes
    • 5)What happens when an exception is thrown?
      • 5.1) Creating try-catch-finally blocks
      • 5.2) Using a method that throws a checked exception
      • 5.3) Using a method that throws a runtime exception
      • 5.4) Using a method that throws an error
      • 5.5) Will a finally block execute even if the catch block defines a return statement?
      • 5.6) What happens if both a catch and a finally block define return statement?
      • 5.7) What happens if a finally block modifies the value returned from a catch block?
      • 5.8) Can a try block be followed only by a finally block?
      • 5.9) Does the order of the exceptions caught in the catch blocks matter?
      • 5.10) Can I rethrow an exception or the error I catch?
      • 5.11) Can I declare my methods to throw a checked exception instead of handling it?
      • 5.12) I can create nested loops, so can I create nested try-catch blocks too?
      • 5.13) Should I handle errors?
    • 6) Best Practices
    • 7) Cheat Sheet
    • 8) Problems
  • 2) Wrapper Classes and Enums
    • 2.1) Creating objects of the wrapper classes
    • Enums
  • 3) Inner Classes
    • 3.1) Static nested class (also called static inner class)
    • 3.2) Inner class (also called member class)
    • 3.3) Anonymous inner class
    • 3.4) Method local inner classes
    • CheatSheet
  • 4) Generics
    • Multiple Type parameters in Generic classes
    • Inheritance using Generics
    • Generic interfaces
    • Generic Methods
    • Bounded type parameters
    • Applications
  • 5) Equals and Hashcode
    • Problems
  • CompareTo method overview
  • Basic DS
    • 1) Simple Array List
    • 2) Simple HashMap
  • 5) Collections Framework - Part 1
    • Introducing the collections framework
    • Working with the Collection interface
      • The core Collection interface
      • Methods of the Collection interface
    • Creating and using List, Set, and Deque implementations
      • List interface and its implementations
      • Iterators
      • Sorting List using custom sorting technique
      • Comparable Interface
      • Custom Sorting using comparator
      • ArrayList - Examples and practice problems
    • Stack
    • Linked List
    • LinkedList Operations
  • 6) Collections Framework - Part 2
    • Sets
      • Set Types
      • Array to Set (vice versa)
    • Maps
    • TreeMap
    • Autoboxing And Unboxing
  • Collections Framework - Part 3
    • Basics : DS , Number System
    • Internal Working
      • HashMap
      • HashSet
  • 7) Reflection API
  • 8) Annotations
  • 9) Reading Input From Various Sources
    • File Handling
    • Reading From Xml
    • Reading From JSON
  • 10) Multi-threading (Concurrency)
    • Protect shared data
    • Thread-safe access to shared data
  • 11) Design Patterns
    • Singleton
    • DI
  • 12) Internal Working of JVM
  • 13) Garbage Collection
  • 14) More on Strings (Buffer and Builder)
  • 15) Cloning and Immutable Class
    • 16) Serialization And Deserialization
    • Untitled
  • JAVA 8
    • Interface Changes
    • Lambda
    • Method Ref
    • Optional
    • Streams
    • Predicates
  • Practice Tests
    • Test - Collections
    • OOPS
    • S-OOPS
Powered by GitBook
On this page
  • How to sort custom Objects using Bubble Sort ? (Example:1)
  • Example 2:

Was this helpful?

  1. 5) Collections Framework - Part 1
  2. Creating and using List, Set, and Deque implementations

Sorting List using custom sorting technique

How to sort custom Objects using Bubble Sort ? (Example:1)

package com.gs.corejava.collections;

interface MyComparable<T> {
	int myCompareTo(T object);
}

class Doctor implements MyComparable<Doctor> {
	private int id;
	private int age;
	private String name;

	/**
	 * @param id
	 * @param age
	 * @param name
	 */
	public Doctor(int id, int age, String name) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Doctor [id=" + id + ", age=" + age + ", name=" + name + "]";
	}

	@Override
	public int myCompareTo(Doctor doctor) {
		if (this.getId() - doctor.getId() == 0) {
			return this.getAge() - doctor.getAge();
		} else {
			return this.getId() - doctor.getId();
		}
	}

}

class MyCollections {
	/**
	 * @param <T>
	 * @param arr
	 */
	public static <T extends MyComparable<T>> void bubbleSort(T[] arr) {
		T c;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j].myCompareTo(arr[j + 1]) >= 0) {
					c = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = c;
				}
			}
		}
	}
}

public class BubbleSort {

	public static void main(String[] args) {

		Doctor doctor = new Doctor(1, 65, "Mohit");
		Doctor doctor1 = new Doctor(4, 26, "Rohit");
		Doctor doctor2 = new Doctor(2, 23, "Amit");
		Doctor doctor3 = new Doctor(6, 45, "Sumit");
		Doctor doctor4 = new Doctor(2, 21, "Pooja");

		Doctor[] doctors = { doctor, doctor1, doctor2, doctor3, doctor4 };
		MyCollections.bubbleSort(doctors);
		for (int i = 0; i < doctors.length; i++) {
			System.out.println(doctors[i]);
		}
	}

}
Doctor [id=1, age=65, name=Mohit]
Doctor [id=2, age=21, name=Pooja]
Doctor [id=2, age=23, name=Amit]
Doctor [id=4, age=26, name=Rohit]
Doctor [id=6, age=45, name=Sumit]

Example 2:

package com.tcs.hdfc.bancs.arraylist;

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

interface MyComaparable<T> {

	public int myCompareTo(T obj);
}

// class User implements MyComaparable<User> {
// private int id;
// private String name;
// private int age;
//
// public User(int id, String name, int age) {
// this.id = id;
// this.name = name;
// this.age = age;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
// public void setAge(int age) {
// this.age = age;
// }
//
// @Override
// public String toString() {
// return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
// }
//
// public boolean equals(Object obj) {
// boolean isSame = false;
// if (obj instanceof User) {
// User user = (User) obj;
// if (this.id == user.id && this.age == user.age &&
// this.name.equals(user.name)) {
// isSame = true;
// }
// }
// return isSame;
// }
//
// // public int myCompareTo(User obj) {
// //
// // if (this.getAge() < obj.getAge()) {
// // return 1; // +ve
// // } else if (this.getAge() == obj.getAge()) {
// //
// // if (this.getId() < obj.getId()) {
// // return 1;
// // } else if (this.getId() == obj.getId()) {
// // return 0;
// // } else {
// // return -1;
// // }
// //
// // } else {
// // return -1; // -ve
// // }
// // }
// public int myCompareTo(User obj) {
// return this.getAge() - obj.getAge() == 0 ? this.getId() - obj.getId() :
// this.getAge() - obj.getAge();
// }
//
// }

class User implements Comparable<User> {
	private int id;
	private String name;
	private int age;

	public User(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	public boolean equals(Object obj) {
		boolean isSame = false;
		if (obj instanceof User) {
			User user = (User) obj;
			if (this.id == user.id && this.age == user.age && this.name.equals(user.name)) {
				isSame = true;
			}
		}
		return isSame;
	}

	// public int myCompareTo(User obj) {
	//
	// if (this.getAge() < obj.getAge()) {
	// return 1; // +ve
	// } else if (this.getAge() == obj.getAge()) {
	//
	// if (this.getId() < obj.getId()) {
	// return 1;
	// } else if (this.getId() == obj.getId()) {
	// return 0;
	// } else {
	// return -1;
	// }
	//
	// } else {
	// return -1; // -ve
	// }
	// }
	public int compareTo(User o) {
		return this.getAge() - o.getAge();
	}
}

public class ArrayListEx1 {

//	public static void modifiedBubbleSort(List<User> users) {
//
//		for (int j = 0; j < users.size(); j++) {
//			for (int i = 0; i < users.size() - 1 - j; i++) {
//				if (users.get(i).myCompareTo(users.get(i + 1)) > 0) {
//					User temp = users.get(i);
//					users.set(i, users.get(i + 1));
//					users.set(i + 1, temp);
//				}
//			}
//
//		}
//	}

	public static void bubbleSort(List<User> users) {

		for (int j = 0; j < users.size(); j++) {
			for (int i = 0; i < users.size() - 1 - j; i++) {
				if (users.get(i).getAge() > users.get(i + 1).getAge()) {
					User temp = users.get(i);
					users.set(i, users.get(i + 1));
					users.set(i + 1, temp);
				}
			}

		}
	}

	public static void main(String[] args) {
		List<User> users = new ArrayList<>();
		User user1 = new User(1, "abcd", 23);
		User user2 = new User(44, "abdd", 24);
		User user3 = new User(8, "name3", 23);
		User user4 = new User(78, "name4", 34);
		User user5 = new User(35, "name5", 67); // 1019

		users.add(user3);
		users.add(user2);
		users.add(user1);
		users.add(user4);
		users.add(user5);

		User user55 = new User(5, "name5", 67); // 10190

		System.out.println(users);

		// will this fun remove
		users.remove(user55);

		System.out.println(users);

		if (user5.equals(user55)) {
			System.out.println("same");
		} else {
			System.out.println("diff");
		}

		// modifiedBubbleSort(users);

		Collections.sort(users);

		System.out.println(users);

	}

}
PreviousIteratorsNextComparable Interface

Last updated 5 years ago

Was this helpful?