Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method named isUnique that takes an array of integers as a parameter and

ID: 3541902 • Letter: W

Question

            Write a method named isUnique that takes an array of integers as a parameter and that returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if a variable called list stores the following values:         

            Then the call of isUnique(list) should return true because there are no duplicated values in this list. If instead the list stored these values:         

                  Then the call should return false because the value 3 appears twice in this list. Notice that given this definition, a list of 0 or 1 elements would be considered unique.         

Explanation / Answer

Link to indented answer with comments : https://www.dropbox.com/s/usn8y3qx8pvhkfs/IsUnique.java


Finction code with comments :

static boolean isUnique(int[] list){
if(list.length == 0 || list.length == 1) return true; // if length of list is 0 or 1, then every element is unique


java.util.HashSet<Integer> numberSet = new java.util.HashSet<Integer>(); // This is a set of integers. Initially it is empty.
for(int i=0; i< list.length; i++){
if(numberSet.contains(list[i])){

// if our set contains that number, then the number is repeated. so return false;
return false;
} else {
numberSet.add(list[i]);

// if our set do not contain integer, then the number has arrived first time. so, add it to set
}
}
return true; // Since all numbers of array passed the loop => No number is repeated. so return true
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote