I implemented both add() and remove() methods from my ArrayList Class.
public void add(Object obj) {
if(data.length - currentSize <= 5) {
increaseListSize();
}
data[currentSize++] = obj;
}
public Object remove(int index){
if(index < currentSize){
Object obj = data[index];
data[index] = null;
int tmp = index;
while(tmp < currentSize){
data[tmp] = data[tmp+1];
data[tmp+1] = null;
tmp++;
}
currentSize--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
However, I don't know how to remove the specific index of my ArrayList of members.
if(temp[0].equals("ADD")) {
memberList.add(member);
fileOut.writeLine(member.toString());
fileLog.writeLine("New member " + member.toString() + " was succesfully added");
}
**else if(temp[0].equals("REMOVE")) {
//memberList.remove(index)
}**
}
Is there any suggestion of how should I get to remove the index of an object of the memberList? Can I modify my remove() method so that I could directly remove the object instead?
One possibility is to overload the existing remove-method with one that takes an Object-parameter. In the method body you have to iterate through the objects of the list and determine the index of the passed object. Then the existing remove-method is called using the previously determined index to remove the corresponding object.
The following implementation removes the first occurrence of the specified object from the list. The removed object is returned. If the list does not contain the object null is returned.
public Object remove(Object obj){
int index = -1;
for (int i = 0; i < data.length; i++) {
if (data[i] == obj) {
index = i;
break;
}
}
if (index != -1) {
return remove(index);
}
return null;
}
Related
I have troubles implementing an Iterator for my TupleHashSet class.
The hashArr attribute stores the Hashsets for my Tuple (Pair) objects. The insert method inserts the Tuples according to the calculated HashCode.
The problem is that my iterator doesn't iterate through the entire HashArr if I insert something with the method.
My teacher told me a tip that my approach is wrong since the HashSet value aren't interested in order. However, I'm not sure what he means with that.
TupleSet
public class TupleSet<T, S> implements Iterable<Tuple<T, S>> {
private final Tuple<T, S>[] hashArr;
public static final int SS = 999;
public TupleHashSet() {
hashArr = new Tuple[SS];
}
#Override
public java.util.Iterator<Tuple<T, S>> iterator() {
return new Iterator(hashArr);
}
class Iterator implements java.util.Iterator<Tuple<T, S>> {
private Tuple<T, S>[] array;
private int index = 0;
Iterator(Tuple<T, S>[] t) {
this.array = t;
}
#Override
public boolean hasNext() {
for (int i = index; i < SIZE; ++i) {
if (array[i] != null) {
return true;
}
}
return false;
}
#Override
public Tuple<T, S> next() {
for (int i = index; i < SIZE; ++i) {
if (hashArr[i] != null) {
index = i + 1;
return hashArr[i];
}
}
throw new NoSuchElementException();
}
}
This answer addresses your question about the iterator not returning all items.
The array index is never incremented, so it will always return the item at index 1, which is index + 1. index must be incremented in the call to next before returning so that the next call starts at the subsequent element in the backing array.
Also, the backing array is not dense (meaning there could be empty slots at arbitrary positions, and that's OK), so the next function has to find the next valid entry, not just give up if the next entry is empty (i.e. null).
Try this instead:
#Override
public Iterator<Tuple<T, S>> iterator() {
Iterator<Tuple<T, S>> it = new Iterator<Tuple<T, S>>() {
private int index = 0;
#Override
public boolean hasNext() {
for (int i = index; i < SIZE; ++i) {
if (hashArr[i] != null) {
return true;
}
}
return false;
}
#Override
public Tuple<T, S> next() {
for (int i = index; i < SIZE; ++i)
if (hashArr[i] != null) {
index = i + 1;
return hashArr[i];
}
}
throw new NoSuchElementException();
}
};
return it;
}
Here's a possible solution.
public boolean hasNext() {
for(; index < SIZE && hashArr[index] == null; index++);
return index < SIZE;
}
I'm creating a resizeable Object Array. Below is my add function in which I pass through the object I want to add into my arraylist.
The function works, however if someone could explain this code
temp[theList.length] = toAdd;
I understand that it's adding the parameter argument to the end of the new Arraylist. But what's confusing me is the index that I pass into temp[]. Shouldn't I be including theList.length + 1 rather than just theList.length?
public boolean add(Object toAdd) {
if (toAdd != null) {
Object[] temp = new Object[theList.length + 1];
for (int i = 0; i < theList.length; i++) {
temp[i] = theList[i];
}
temp[theList.length] = toAdd;
theList = temp;
return true;
} else {
System.out.println("Invalid type");
return false;
}
}
Explanation for the add method:
Assume, the size of the theList is 10.
They have created an temp array which takes size as theList + 1, so size of temp is 11.
Now, objects are added to the temp except for the last element tem[10].
For adding the last element, you can use any of the 2 ways:
temp[theList.length] //temp[10]
Or
temp[temp.length-1] //temp[10]
They used the 1st way to add the toAdd object.
You could use a standard method Arrays.copyOf which immediately creates a copy of the input array with the new size (in this case, the length is increased):
import java.util.Arrays;
//...
public boolean add(Object toAdd) {
if (toAdd != null) {
int oldLength = theList.length;
theList = Arrays.copyOf(theList, oldLength + 1);
theList[oldLength] = toAdd;
return true;
} else {
System.out.println("Cannot add null object");
return false;
}
}
Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)
Is the statement list.contains("are") (have commented it) being checked by matching character to character ?
import java.util.*;
class Tester {
public static void main(String args[]) {
String arr[] = {"how","are","you","veena"};
LinkedList<String> list = new LinkedList<String>();
for(String s : arr) {
list.add(s);
}
if(list.contains("are")) { // STATEMENT
System.out.println("Found !");
}
}
}
In this program if statement works. How does the contain method work ?
That method iterates over the linked list, and compare each element with the element passed by invoking equals() method. In this case, it will invoke String#equals(Object) method.
this is implementations of method contains and indexOf from LinkedList
public boolean contains(Object o) {
return indexOf(o) != -1;
}
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
so as you see it is iterating trough array till it finds first matching element
Creating an instance of an object (o) and adding it to an Arraylist (arrayList) works fine. However, the remove function doesn't work.
arrayList.add(o); // works
arrayList.remove(o); // does nothing
What am I missing?
ArrayList.remove() look like this:
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
So, if your Object has default equals(), then this cant work. All object are diffrent. Add equals() to your Object class.