Name.java Source code

Java tutorial

Introduction

Here is the source code for Name.java

Source

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

class Name implements Comparable<Name> {
    private String firstName;
    private String lastName;

    public Name(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public int compareTo(Name otherName) {
        if (this.firstName.compareTo(otherName.firstName) == 0) {
            return this.lastName.compareTo(otherName.lastName);
        } else {
            return this.firstName.compareTo(otherName.firstName);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Name name = new Name("A", "C");
        Name name1 = new Name("A", "B");
        Name name2 = new Name("C", "F");
        Name name3 = new Name("D", "A");
        Name name4 = new Name("Ca", "D");
        Name name5 = new Name("Cc", "Z");
        Name name6 = new Name("Cc", "W");

        Name nameArray[] = { name, name1, name2, name3, name4, name5, name6 };
        List<Name> names = new ArrayList<Name>(Arrays.asList(nameArray));

        Collections.sort(names);

        for (Name n : names) {
            System.out.println(n.getFirstName() + " " + n.getLastName());
        }
    }
}