This method is used in a class that extends a LinkedList pub
This method is used in a class that extends a LinkedList.
public Object[] toArray():
This method returns a new array that contains all the items in the set. If the size of the set is 0, return an empty array. The objects in the set are unique (i.e., no duplicates), so the returned array cannot contain duplicates.
How would I complete this method? This is what I have so far and I\'m pretty sure I\'m a ways off.
public Object[] toArray() {
// TODO This method returns a new array that contains all the items in the set.
// If the size of the set is 0, return an empty array. The objects in the set are unique
//(i.e., no duplicates), so the returned array cannot contain duplicates.
Object[] obj = new Object [size];
if(obj.length == 0){
return obj;
}
for(int i = 0; i < obj.length; i++){
if(obj[i] == obj){
obj = null;
}
else{
return obj;
}
}
return obj;
}
Solution
import java.util.Arrays;
public class Duplicates{
static void eliminatesDuplicates(int[] list)
{
int len = list.length;
//Comparing each element with all other elements
for (int i = 0; i < len; i++) {
for (int j = i+1; j < len; j++) {
//If any two elements are found equal
if(list[i] == list[j]){
//Replace duplicate element with last unique element
list[j] = list[len-1];
len--;
j--;
}
}
}
//Copying only unique elements
int[] withoutDuplicates = Arrays.copyOf(list, len);
System.out.print(\"Distinct numbers are :\");
for (int i = 0; i < withoutDuplicates.length; i++)
{
System.out.print(withoutDuplicates[i]+\",\");
}
}
public static void main(String[] args)
{
eliminatesDuplicates(new int[] {4, 3, 2, 4, 9, 2});
//eliminatesDuplicates(new int[] {1, 2, 1, 2, 1, 2});
}
}
![This method is used in a class that extends a LinkedList. public Object[] toArray(): This method returns a new array that contains all the items in the set. If This method is used in a class that extends a LinkedList. public Object[] toArray(): This method returns a new array that contains all the items in the set. If](/WebImages/35/this-method-is-used-in-a-class-that-extends-a-linkedlist-pub-1105261-1761584840-0.webp)
![This method is used in a class that extends a LinkedList. public Object[] toArray(): This method returns a new array that contains all the items in the set. If This method is used in a class that extends a LinkedList. public Object[] toArray(): This method returns a new array that contains all the items in the set. If](/WebImages/35/this-method-is-used-in-a-class-that-extends-a-linkedlist-pub-1105261-1761584840-1.webp)