Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws java.lang.Exception {
        List<Person> people = new ArrayList<Person>();
        people.add(new Person("J", "S"));
        people.add(new Person("J", "S"));
        people.add(new Person("J", "F"));
        people.add(new Person("J", "W"));
        people.add(new Person("J", "B"));
        Set<Object> seen = new HashSet<Object>();
        for (Person p : people) {

            Wrap wrap = new Wrap(p);
            if (seen.add(wrap)) {
                System.out.println(p + " is new");
            } else {
                System.out.println(p + " is a duplicate");
            }
        }
    }
}

class Wrap {
    Person thisPerson;

    public Wrap(Person p) {
        thisPerson = p;
    }

    public int hashCode() {
        return thisPerson.getFirst().hashCode();
    }

    public boolean equals(Object o) {
        Wrap other = (Wrap) o;
        return other.wrapped().getFirst().equals(thisPerson.getFirst());
    }

    public Person wrapped() {
        return thisPerson;
    }
}

class Person {
    private String first;
    private String last;

    public String getFirst() {
        return first;
    }

    public String getLast() {
        return last;
    }

    public Person(String f, String l) {
        first = f;
        last = l;
    }

    public String toString() {
        return first + " " + last;
    }
}