Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        MyObject a1 = new MyObject("a", 1);
        MyObject a2 = new MyObject("a", 2);
        MyObject a3 = new MyObject("a", 3);
        MyObject b1 = new MyObject("b", 1);
        MyObject b2 = new MyObject("b", 2);
        MyObject b2a = new MyObject("b", 2);
        MyObject nullLevel = new MyObject("a", null);
        MyObject nullName = new MyObject(null, 2);
        SortedSet<MyObject> set = new TreeSet<MyObject>();
        set.add(a1);
        set.add(a2);
        set.add(a3);
        set.add(b1);
        set.add(b2);
        set.add(b2a);
        set.add(nullLevel);
        set.add(nullName);
        System.out.println(Arrays.toString(set.toArray()));
    }
}

class MyObject implements Comparable<MyObject> {
    private String name;
    private Integer level;

    public MyObject(String name, Integer level) {
        this.name = name;
        this.level = level;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((level == null) ? 0 : level.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MyObject other = (MyObject) obj;
        if (level == null) {
            if (other.level != null)
                return false;
        } else if (!level.equals(other.level))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public int compareTo(MyObject o) {
        if (level == null) {
            return new MyObject(name, 0).compareTo(o);
        }
        if (name == null) {
            return new MyObject("", level).compareTo(o);
        }

        if (level.equals(o.level)) {
            return name.compareTo(o.name);
        } else {
            return level.compareTo(o.level);
        }
    }

    public String toString() {
        return level + " " + name;
    }

}