Learn The Techniques For SORTING CUSTOM OBJECTS In Java

Опубликовано: 28 Сентябрь 2024
на канале: Begin Secure
496
14

Learn the techniques for sorting custom objects in Java. What is the difference between the Comparator and Comparable interfaces and which one should you use? Find out what situations can cause a runtime exception that will cause your application to crash. And as always, what are the security implications of sorting objects. When writing code, remember to always Begin Secure!!

#IT #Development #SoftwareDevelopment #JavaProgramming #JavaTutorial #AppplicationSecurity #AppSec #appsecurity #informationsecurity #infosec

Chapters

00:00 Introduction
00:32 Overview
00:52 Java Comparable vs Comparator
01:10 Java classes implementing the Comparable interface
02:30 What's the purpose of Comparator?
03:13 Coding example using Comparable and Comparator
05:47 Example code using the Comparator interface to sort objects
12:39 Application security discussion of the Comparator and Comparable interfaces

The question today is: how can you sort an arraylist of custom objects by a property.

And just to be clear, we want to be able to sort the arraylist of custom objects, regardless of the data type.

Great question

To answer the question, we need to discuss the difference between comparable vs comparator
Java.lang.comparable is an interface

Classes that implement the comparable interface provde a natural ordering of the data so they can be sorted automatically

When we say automatically, it simple means that the order is obvious to anyone.

For example, here we see some of the java classes that implement the comparable interface

They include classes such as byte, long, interger, short, double float, big inteter and bigdecimal.

Keep in mind that the numeric types – long, integer, float, double, etc – refer to the class wrappers and not the primitive types

The natural ordering for these classes is a signed numerical ordering

Next is character, the order for this class is unsigned numerical

The Boolean wrapper class also implements the comparable interface and in this case false comes before true

And we see a few more examples including file, string, date and collation key

If a class does not implement the comparable interface, you will get a classcast exception at runtime if you try to sort them.

The comparable interface consists of the following method

public int compareTo

which takes a type as an argument.