Created
October 1, 2018 09:13
-
-
Save jimytc/e7559e56c8ba041879a7edc13aacc08e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
public class Pen implements Comparable<Pen> { | |
private String serialNumber; | |
private int length; | |
public Pen(String serialNumber, int length) { | |
this.serialNumber = serialNumber; | |
this.length = length; | |
} | |
@Override | |
public int compareTo(Pen target) { | |
if (length > target.length) { | |
return 1; | |
} else if (length < target.length) { | |
return -1; | |
} else { | |
return 0; | |
} | |
} | |
@Override | |
public boolean equals(Object target) { | |
if (target == this) return true; | |
if (!(target instanceof Pen)) return false; | |
Pen p = (Pen) target; | |
return serialNumber.equals(p.serialNumber); | |
} | |
@Override | |
public String toString() { | |
return String.format("SN: %s, length: %d", serialNumber, length); | |
} | |
public static void main(String[] argv) { | |
ArrayList<Pen> pensInMyPocket = new ArrayList<>(5); | |
pensInMyPocket.add(new Pen("a", 10)); | |
pensInMyPocket.add(new Pen("a", 4)); | |
pensInMyPocket.add(new Pen("b", 16)); | |
pensInMyPocket.add(new Pen("c", 7)); | |
pensInMyPocket.add(new Pen("b", 1)); | |
System.out.println("Before sort by length:"); | |
for (Pen pen : pensInMyPocket) { | |
System.out.println(String.format("\t%s", pen)); | |
} | |
Collections.sort(pensInMyPocket); | |
System.out.println("After sort by length:"); | |
for (Pen pen : pensInMyPocket) { | |
System.out.println(String.format("\t%s", pen)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment