Question

In: Computer Science

CS 209 Data Structure 5. Consider the Pair class covered in class: class Pair {    ...

CS 209 Data Structure

5. Consider the Pair class covered in class:

class Pair

{

    public A first;

    public B second;

    public Pair(A a, B b)

    {

        first = a;

        second = b;

    }

    public void setFirst(A a)

    {

        first = a;

    }

    public A getFirst()

    {

        return first;

    }

    public void setSecond(B b)

    {

        second = b;

    }

    public B getSecond()

    {

        return second;

    }

}

a. Create a toString() method inside the Pair class.

b. Create an equals() method inside the Pair class.

c. Create a hashCode() method inside the Pair class.

d. Create a HashSet of Pair and insert a few elements including duplicates.

Verify that the HashSet removes all the duplicates.

Solutions

Expert Solution

A.java:

import java.util.Objects;

public class A {
    String str;

    /**
     * constructor with single parameter
     * @param str
     */
    A(String str) {
        this.str = str;
    }

    /**
     * convert current object to string
     * @return
     */
    public String toString() {
        return str;
    }

    /**
     * function to equality check
     * @param o
     * @return
     */
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        A a = (A) o;
        return Objects.equals(str, a.str);
    }

    public int hashCode() {
        return Objects.hash(str);
    }
}

B.java:

import java.util.Objects;

public class B {
    String str;

    /**
     * constructor with single parameter
     * @param str
     */
    B(String str) {
        this.str = str;
    }

    /**
     * convert current object to string
     * @return
     */
    public String toString() {
        return str;
    }

    /**
     * function to equality check
     * @param o
     * @return
     */
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        B b = (B) o;
        return Objects.equals(str, b.str);
    }

    public int hashCode() {
        return Objects.hash(str);
    }
}

Pair.java:

import java.util.Objects;

/**
 * class pair
 */
class Pair

{
    public A first;
    public B second;

    /**
     * constructor with two parameter
     * @param a
     * @param b
     */
    public Pair(A a, B b)
    {
        first = a;
        second = b;
    }

    /**
     * setter method for first
     * @param a
     */
    public void setFirst(A a)
    {
        first = a;
    }

    /**
     * getter method for first
     * @return
     */
    public A getFirst()
    {
        return first;
    }

    /**
     * setter method for second
     * @param b
     */
    public void setSecond(B b)
    {
        second = b;
    }

    /**
     * getter method for second
     * @return
     */
    public B getSecond()
    {
        return second;
    }

    /**
     * function to get string
     * @return
     */
    public String toString() {
        return "Pair{" +
                "first=" + first +
                ", second=" + second +
                '}';
    }

    /**
     * check whether two pairs are equal or not
     * @param o
     * @return
     */
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pair pair = (Pair) o;
        return Objects.equals(first, pair.first) &&
                Objects.equals(second, pair.second);
    }

    /**
     * function to get hash code of current object
     * @return
     */
    public int hashCode() {
        return Objects.hash(first, second);
    }
}

Driver.java:

import java.util.HashSet;

public class Driver {
    public static void main(String[] args) {
        // create new hashset of pair
        HashSet<Pair> hashSet = new HashSet<>();

        // add new pair
        hashSet.add(new Pair(new A("A0"), new B("B0")));

        // add new pair
        hashSet.add(new Pair(new A("A1"), new B("B1")));

        // add duplicate
        hashSet.add(new Pair(new A("A1"), new B("B1")));

        // add new pair
        hashSet.add(new Pair(new A("A2"), new B("B2")));

        // addd duplicate
        hashSet.add(new Pair(new A("A2"), new B("B2")));

        // print hash set
        for (Pair p: hashSet) {
            System.out.println(p);
        }
    }
}

Output:


Related Solutions

CS 209 Data Structure 3. a. Create a class named Point3D that contains 3 instance variables...
CS 209 Data Structure 3. a. Create a class named Point3D that contains 3 instance variables x, y, and z. b. Create a constructor that sets the variables. Also, create get and set methods for each variable. c. Create a toString() method. d. Make Point3D implement Comparable. Also, create a compareTo(Point3D other) method that compares based on the x-coordinate, then y-coordinate for tiebreakers, then z-coordinate for tiebreakers. For example, (1, 2, 5) comes before (2, 1, 4), which comes before...
CS 209 Data Structure 2. Create a method that takes a HashMap and returns the sum...
CS 209 Data Structure 2. Create a method that takes a HashMap and returns the sum of the keys of the HashMap. 3. Create a method that takes a HashMap and returns the sum of all keys and values of the HashMap. For example, if the input is [1=9, 3=6, 4=9, 6=8, 7=6] then the method should return 59.
CS 209 Data Structure 1. Create a method that takes an ArrayList of Integer and returns...
CS 209 Data Structure 1. Create a method that takes an ArrayList of Integer and returns a sorted copy of that ArrayList with no duplicates. Sample Input: {5, 7, 4, 6, 5, 6, 9, 7} Sample Output: {4, 5, 6, 7, 9}
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String...
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String and returns a copy of that ArrayList with no duplicates. The relative ordering of elements in the new ArrayList should be the same. Sample Input: {"qwerty", "asdfgh", "qwer", "123", "qwerty", "123", "zxcvbn", "asdfgh"} Sample Output: {"qwerty", "asdfgh", "qwer", "123", "zxcvbn"}
CS 209 Data Structure 1. show how to apply a selection sort on {45, 11, 50,...
CS 209 Data Structure 1. show how to apply a selection sort on {45, 11, 50, 59, 60, 2, 4, 7, 10}. 2. show how to apply a Insertion sort on {45, 11, 50, 59, 60, 2, 4, 7, 10}. 3. show how to apply a Bubble sort on {45, 11, 50, 59, 60, 2, 4, 7, 10}. 4. show how to apply a Merge sort on {45, 11, 50, 59, 60, 2, 4, 7, 10}. 5. show how to...
CS 209 Data Structure (Postfix notation) Postfix notation is a way of writing expressions without using...
CS 209 Data Structure (Postfix notation) Postfix notation is a way of writing expressions without using parentheses. For example, the expression (1 + 2) * 3 would be written as 1 2 + 3 *. A postfix expression is evaluated using a stack. Scan a postfix expression from left to right. A variable or constant is pushed into the stack. When an operator is encountered, apply the operator with the top two operands in the stack and replace the two...
Implement a class named stack pair that provides a pair of stacks. Make the class a...
Implement a class named stack pair that provides a pair of stacks. Make the class a template class. So, you will have two files: stack pair.h and stack pair.template, following the style of the text. The basic idea is that two stacks can share a single static array. This may be advantageous if only one of the stacks will be in heavy use at any one time. • The class should have various methods to manipulate the stack: T pop...
Suppose that a​ researcher, using data on class size ​(CS​) and average test scores from 100...
Suppose that a​ researcher, using data on class size ​(CS​) and average test scores from 100 ​third-grade classes, estimates the OLS regression. TestScore = 515.1960 + (-5.7618) x CS, R^2 = 0.11, SER = 11.4 (20.1960) (2.3426) 1. The p-value for the two-sided test for the null hypothesis H0 : B1 = 0 is ? (Round to four decimal places) 2. The p-value for the two-sided test of the null hypothesis H0 : B1 = -5.5 ? (Round to four...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf Requirement: - deal with single digit positive integers only. Operands and operators are fully separated by space. - learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/ - learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/ - take in a postfix arithmetic expression from cin, and evaluate its value....
Consider a mutual fund with $209 million in assets at the start of the year and...
Consider a mutual fund with $209 million in assets at the start of the year and with 10 million shares outstanding. The fund invests in a portfolio of stocks that provides dividend income at the end of the year of $3 million. The stocks included in the fund's portfolio increase in price by 9%, but no securities are sold, and there are no capital gains distributions. The fund charges 12b-1 fees of 1.00%, which are deducted from portfolio assets at...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT