How can I override remove method for Set? - java

I'm trying to write the remove method for Set but it doesn't work when I test it. Am I doing it wrong? the size doesn't reduce after I remove the element.
public class MySet<T> implements Set<T> {
private T[] arrayB;
private int elements;
#Override
public boolean remove(Object f) {
T h = (T) f;
for (T z : arrayB) {
if(z == h) {
z = null;
}
}
return true;
}
#Override
public int size() {
int count = 0;
for(int arr = 0; arr < arrayB.length; arr++){
if(arrayB[arr] != null) {
count++;
}
}
return count;
}
The test code is:
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
}

Your size method relies on whether the element is null to decide whether to count it. Assuming that you are attempting to place a null in the array, you're doing it wrong. All you've done is assign null to z, which is just a local variable. The array is not changed.
You must use a traditional for loop and use an array access expression to assign null to the array element. You'll also want to call equals instead of using == to find the element.
for (int i = 0; i < array.length; i++)
{
if (array[i] != null && array[i].equals(h))
{
array[i] = null;
}
}
Depending on whether you want to remove all elements that match, or just the first one, you may consider adding a break statement inside the if.

Related

searchForItemInArray in Java - Nested For Loop

Java says ''the type of the expression must be Array type but it resolved to Int"
I'm looking to do a nested For Loop for the solution, but any other more more elegant suggestions are also welcome.
public class ArraySearch {
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= needle; i++) {
for (int j = 0; j < haystack.length; j++) {
if (needle[i] == haystack[j]) {
}
}
}
return -1;
}
}
needle is an Int variable so isn't part of an array.
The answer to fix the IF statement was needle == haystack[j]
If searching for an item in an arrray is actually what you want, then you don't need a nested for loop.
If the needle is the item that you are searching for and the haystack is the array, you need to parse the array one time, using only one for loop and check at each step if the current item is equal to the searched element.
public static int searchForItemInArray(int needle, int[] haystack) {
for (int i = 0; i < haystack.length; i++) {
if (needle == haystack[i]) {
// return the position of the item in the array.
return i;
}
}
return -1;
}
It looks like you are searching index of the needle it that array. If it is true, than your code can be as follows:
public static int searchForItemInArray(int needle, int[] haystack) throws Exception {
for (int i = 0; i <= haystack.length; i++) {
if (needle == haystack[j]) {
return i;
}
}
return -1;
}

How to address ArrayIndexOutOfBoundsException without using try-catch?

I was given a homework assignment to check if all the elements of an array are the same value. I return true if they are, otherwise I return false. I was instructed to return true if the array was empty. The following code works in all cases except when the array has no elements - a length of zero. How could I go about addressing this issue?
public static boolean allSame (double[] list) {
double sameReference = list[0];
for (int i = 0; i < list.length; i++) {
if (list [i] != sameReference)
return false;
}
return true;
}
Just add an empty check
public static boolean allSame (double[] list) {
if (list.length() == 0){
return true;//list empty so return true
}
double sameReference = list[0];
for (int i = 0; i < list.length; i++) {
if (list [i] != sameReference)
return false;
}
return true;
}

How to write a remove method?

Write a method called get which will return an element from the given index. Returns -1 if the index is out-of-bounds.
Write a method called remove which will remove an element from the given index. Returns -1 if the index is out-of-bounds. Data should be shifted accordingly during removal.
//This is the get method
public int get(int index){
if(index < 0 || index >= size) {
return -1;
}else {
return data[index];
}
}
//This is the remove method
public int remove(int index){
if(index < 0 || index >= size){
return -1;
}else {
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
}
}
This is as far as I got. Not sure how to proceed with the code. I'd appreciate if someone could guide me through. Thank you!
So far, you have the right idea. I am going to assume based on your syntax, that you are using an array. Your get() method looks good, but you are missing some code from your remove() method.
public int remove(int index){
//check for out-of-bounds
if(index < 0 || index >= size) //assumes size is set to the size of the array
{
return -1; }
else
{
for(int i = index; i < size-1; i++){
data[i] = data[i+1]; }
data[size-1] = 0; //assuming the array contains numbers, if not replace '0' with null
}
}
You need to replace the following :
for(int i = 0; i < size-1; i++) {
index[i] = index[i+1];
}
with:
for(int i = index; i < size-1; i++) {
data[i] = data[i+1];
}
Start the loop with index
index[i] won't compile. Should be data[i] probably.
Note:
This will not delete the last element. You need to specifically check for it.
public class MyList<T> {
T[] items = (T[])new Object[10];
public int size() {
int counter=0;
for (int i = 0; i < items.length; i ++) {
if (items[i] != null) {
counter ++;
}
}
return counter;
}
public void remove(int t) {
for (int i = t; i < items.length-1; i++) {
items[i]=items[i+1];
}
items[items.length-1]=null;
items= Arrays.copyOf(items,size());
}
}

How to access elements in a generic arraylist of arrays

I have been trying to access the elements of several arrays that are held within an array list. I am able to access it regularly, but the problem comes when I use generic type E to account for different data types. This gives me a class cast exception. If I change the type of tempStart and tempScan and corresponding casts to int[] (since that is what I am using to pass in) it runs.
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
if (list.get(0).getClass().isArray()) {
System.out.println(" I am an array!");
//go through the arrays and make sure they are
//not the same, remove any that are the same
//make flag to see if something is different
boolean matching;
for (int idx = 0; idx < list.size() - 1; idx++) {
E[] tempStart =(E[])list.get(idx);
for (int k = idx + 1; k < list.size(); k++) {
matching = true;
E[] tempScan = (E[])list.get(k);
for (int index = 0; index < tempStart.length; index++) {
if (tempStart[index] != tempScan[index]) {
matching = false;
}
}
if (matching) {
list.remove(tempScan);
k--;
}
}
}
You are trying to cast E to E[] and it's obviously not correct. Try something like:
import java.lang.reflect.Array
...
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
ArrayList<E> retList = new ArrayList<>(list.size());
if (list.isEmpty()) return retList;
if (list.get(0).getClass().isArray()) {
boolean matching;
for (int idx = 0; idx < list.size() - 1; ++idx) {
E tempStart = list.get(idx);
for (int k = idx + 1; k < list.size(); k++) {
matching = true;
E tempScan = list.get(k);
int tempStartLen = Array.getLength(tempStart);
for (int index = 0; index < tempStartLen; index++) {
if (Array.get(tempScan, index) != Array.get(tempStart, index)) {
matching = false;
}
}
if (matching) {
list.remove(tempScan);
k--;
}
}
}
return retList;
} else {
throw new IllegalArgumentException("List element type expected to be an array");
}
}
However because we are using Java Reflection Array to manipulate the array operation, using generic E doesn't make sense here. You can simple declare it as ArrayList<Object>
Updates: as #afsantos comments below, the parameter type ArrayList could be declared as ArrayList<?> as nothing is going to be insert into it.

Java logic issues

I'm working on a method that finds the first instance of a given value and returns its position. It works for some cases, but if I give it an array of [1,2,3], and set the value to 2, it returns 0, instead of 1. I'm not sure why, either. Here is the code:
int b = 0;
for(int a = 0; a < values.length; a++) {
if (values[a] == find){
b++;
}
}
return b-1;
Thanks in advance!
Its because you are returning b-1. In fact, if you need to find the same instance and return the index, you wont even need the variable b. You could achieve this with something like this:
for( int a = 0; a < values.length; a++) {
if (values[a] == find){
return a;
}
}
return -1 // Notfound
}
Add the return -1 line for when a value is not found, to use as a sentinel value.
Try
for( int a = 0; a<values.length; a++) {
if (values[a] == find){
return a;
}
}
Why not return a itself instead of doing b-1;
Maybe you can add a break statement too to stop iterating as you just need the position of first instance
int b=0,result;
for( int a = 0; a<values.length; a++)
{
if (values[a] == find)
{
result=a;
break;
}
}
return result;

Categories

Resources