Adding object to last element of arraylist - java

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;
}
}

Related

Testing if a string is a palindrome using a stack

I am attempting to take a user inputted word, ad it to a stack and then check to see if that word is a palindrome. I am attempting to pop everything off the stack and onto a new string and then compare the strings. I believe my current issue is that my pop() function doesn't actually return a value. It actually just cuts off the tail node and then reprints the string without the tail node. I guess my question is, how do I write my pop() function so that it returns the "popped" value?
Here is my main method
Scanner input = new Scanner(System.in);
Stack_Scott_Robinson<Character> myList = new Stack_Scott_Robinson<Character>(); //create a list object
System.out.println("Enter a string: ");
String s = input.next();
for (int i = 0; i < s.length(); i++){
myList.push(s.charAt(i));
}
String reverseInput = "";
while (!myList.isEmpty()){
reverseInput = reverseInput + myList.Pop();
}
if (s.equals(reverseInput)){
System.out.println("This is a palindrome");
}else{
System.out.println("This is not a palidrome");
System.out.print("Would you like to re-run code with different input string(y/n)?");
another = input.next();
}
Here is my pop() method
public void Pop()
{
Node countList = end; //set "count" node at the front of the list
int size = 0; //initialize the size variable
//moves the count node down the list and increments the size variable
while (countList != null)
{
countList = countList.next;
size++;
}
if (size == 0){ //empty list
System.out.println("error: empty list");
}else if (size == 1) //one node list
{
top = null;
end = null;
System.out.println("list is now empty");
}
else{
Node current = end;//set a current node at the front of the list
for (int i = 0; i<size-2; i++)//-2 because the list starts at 0 and we want the second to last position
{
current = current.next;//moves the current node down the list until it is
}
Node temporary = current.next; //the second to last position
Node temp = top;//create a new node space
top = current;//set the new node equal to the second to last position
top.next = null;//sets the node as the tail
}
}
Here is how java.util.Vector does it (java.util.Stack extends Vector)
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
and
public synchronized void removeElementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
modCount++;
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
In the pop method, you can see that we know what object to remove because they get it using peek(); Then they just remove the element at the end of the vector. Hopefully this helps. I'm not sure how you are representing your Stack under the hood, so I can't really give you a better answer without that.

How to remove an object from arrayList

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;
}

add to array and return boolean

I would like to add an object to an array and return true if the array is not full so the item can be added, and false if the array is full of items.
What I have right now I believe is only partially correct.
private Object[] theList;
//constructors omitted
#Override
public boolean add(Object toAdd) {
for(int i=0; i < theList.length;i++){
if(toAdd != null){
theList[i] = toAdd;
}
}
return true;
}
I think using an element counter would be the right way to go to keep track
of the number of element currently in the array.
The method is overridden from an interface, if that matters.
Not sure if it is returning true based on the on the loop and conditions or just returning true no matter what.
It looks like you're trying to find the first null value in your array, and if such a value exists, replace it with your toAdd object and return true.
The code for that would be something along the lines of:
private Object[] theList;
#Override
public boolean add(Object toAdd) {
for(int i=0; i < theList.length; i++) {
if(theList[i] == null){
theList[i] = toAdd;
return true;
}
}
return false;
}
If you also want to return false in case your toAdd object is null, for performance reasons, you should check for that before looping over the array:
#Override
public boolean add(Object toAdd) {
if (toAdd != null) {
for(int i=0; i < theList.length; i++) {
if(theList[i] == null){
theList[i] = toAdd;
return true;
}
}
}
return false;
}
Obviously it's more convenient to use an ArrayList instead.
You Have not initialized Your object[] ObjectArray theList. So, It won't be able to add new element to this.
Here I am Giving a Solution For Your Problem Using ArrayList Class. ArrayList is an auto Growable Array Increased Its Size Dynamically at Runtime.
private ArrayList<Object> theList = new ArrayList<>(); //A Auto Growable Array Increased Its Size Dynamically at Runtime.
//constructors omitted
#Override
public boolean add(Object toAdd) {
if(toAdd != null){
theList.add(toAdd);
return true; //returns true id Object is added to theList.
}else
return false; //returns false if Object is Null .
}
Code to Get ArrayList Size
theList.size() //Use This Code to know the Size of Array List.
First of all you have to initialize the array. Otherwise it will return you a Null Pointer Exception. Here is my code. Hope it will help...
class Demo{
static boolean result;
public static void main(String args[]){
Object ob= new Object();
result = A.add(ob);
System.out.println(result);
Object ob1= new Object();
result = A.add(ob1);
System.out.println(result);
}
}
class A{
static private Object[] theList = new Object[10];
public static boolean add(Object ob){
boolean result = false;
for(int i=0; i<theList.length; i++){
if(ob != null){
theList[i] = ob;
result = true;
}
}
return result;
}
}
Default value of array of objects is null. So that you can check whether an element is null or not.
for(int i=0:i<theList.length;i++) {
if(theList[i] == null && toAdd!=null) // Element is null or not
theList[i]=toAdd;
return true;
}
return false;
if element is null then array is still empty and you can put value there and return true.
You may want to consider using an ArrayList as they are expandable and do not have a set size. So whenever you add something it just grows the ArrayList instead of changing the value of an index.
Edited second time, another solution as per suggestions by peer contributers. I have also posted understanding of the questions in the comments. Please suggest if there is any aberration in the understanding.
Kindly see one possible solution:
public class TestCode {
public static void main(String[] args) {
/*
* Question:
* I would like to add an object to an array and
* return true if the array is not full so the item can be added,
* and false if the array is full of items.
*/
Object[] objects = new Object [] {1, 2, null, 4, 5, null , 7};
SomeClass someClass = new SomeClass(objects);
// just for sake of passing;
Integer toAdd = 10;
boolean isNotFull = someClass.add(toAdd);
System.out.println("Array after adding: "+Arrays.toString(objects));
System.out.println("Array is Not full:"+isNotFull);
isNotFull = someClass.add(toAdd);
System.out.println("Array after adding: "+Arrays.toString(objects));
System.out.println("Array is Not full:"+isNotFull);
isNotFull = someClass.add(toAdd);
System.out.println("Array after adding: "+Arrays.toString(objects));
System.out.println("Array is Not full:"+isNotFull);
}
}
class SomeClass {
private Object[] theList;
//constructors omitted
public SomeClass(Object[] theList) {
this.theList = theList;
}
/*
* returns true if array is not full and element is inserted.
*/
public boolean add(Object toAdd) {
int i = 0;
boolean flag = false; // if flag is true, the array is not empty
// question says:
// "I would like to add an object to an array"
// means we need to first find an empty slot to insert in the array
for( ; i < theList.length;i++){
// to check if there is any first empty space in the array
// so that the element can be inserted.
// (finding the empty slot
if(theList[i] == null){
// to check if elements passed as an aargument itself is false
if (toAdd!=null) {
theList[i] = toAdd;
break;
}
}
}
for (;i <theList.length; i++) {
if(theList[i] == null){
flag = true;
}
}
return flag;
}
}
Solution:
Output of the code as I get:
Array after adding: [1, 2, 10, 4, 5, null, 7]
Array is Not full:true
Array after adding: [1, 2, 10, 4, 5, 10, 7]
Array is Not full:false
Array after adding: [1, 2, 10, 4, 5, 10, 7]
Array is Not full:false

Adding into a sorted `linkedList`

Folks, my method needs to add a new element into already a sorted list, i.e. in a proper position. The point is the method checks the lowest row index and then compares its cols. For example,
board.set(2,2, 11);
board.set(-1,0,22);
board.set(-1,2,33);
board.set(1,0,44);
board.set(3,0,55);
board.set(3,1,66);
board.set(3,3,77);
board.set(3,2,88);
board.set(-1,1,99);
The result should be:
[(-1,0,22), (-1,1,99), (-1,2,33), (1,0,44), (2,2,11), (3,0,55), (3,1,66), (3,2,88), (3,3,77)]
But my program prints this:
[(-1,0,22), (-1,1,99), (3,2,88), (3,3,77), (3,1,66), (3,0,55), (1,0,44), (-1,2,33), (2,2,11)]
i.e. it does not put the objects into the proper positions.
I have a LinkedList<RowColElem<T>>rowColSeq where the objects are added and put into a proper position "on the go". What is my code missing?
NOTE: Im not allowed to use comparators, comparable interface!
LinkedList<RowColElem<T>> rowColSeq; // Is not empty, already contains objects!
private void sortedRowColSeq(int row, int col, T x){
RowColElem<T> object = new RowColElem<T>(row, col, x);
ListIterator<RowColElem<T>> iter = rowColSeq.listIterator();
RowColElem<T> inListObject;
boolean added = false;
while(iter.hasNext()){
inListObject = iter.next();
if(object.getRow() < inListObject.getRow()){
iter.previous();
iter.add(object);
undoStack.push(object);
added = true;
break;
}
else if(object.getRow() == inListObject.getRow()){
if(object.getCol() < inListObject.getCol()){
iter.previous();
iter.add(object);
undoStack.push(object);
added = true;
}
}
else{
iter.add(object);
undoStack.push(object);
added = true;
break;
}
}
}
You may not add if the new element is greater than some element. You must enter before one that is greater, or at the end.
boolean added = false;
while(iter.hasNext()){
inListObject = iter.next();
if(object.getRow() < inListObject.getRow() ||
object.getRow() == inListObject.getRow()) &&
object.getCol() < inListObject.getCol() ){
if( iter.hasPrevious() ){
iter.previous();
iter.add(object);
} else {
rowColSeq.addFirst( object );
}
undoStack.push(object);
added = true;
break;
}
}
if( ! added ){
rowColSeq.addLast(object);
undoStack.push(object);
added = true;
}
The approach using iter.previous() is doomed to fail under certain circumstances so I added a test and alternative code.

Delete element from an array in java

I have an array and I am implementing a priority queue with it. Now, I cam not shift the elements(since only the front pointer has to move).
I tried that by adding null to that array position but it just does not work since I have used Arrays.sort(arr) methods and if I do make the position null, it gives NullPointerException.
Here is how my code looks:
public static void remove() {
//Priorityy x = arr[front];
arr[front] = null;
front--;
//return x;
}
public int compareTo(Priorityy pe) {
if (this == null || pe == null)
return 0;
else {
if (this.key < pe.key) {
return 1;
} else if (this.key > pe.key) {
return -1;
} else {
return 0;
}
}
}
Where did I go wrong?
Use Arrays.copyOfRange to get an array without the first element (front) as follows:
arr = Arrays.copyOfRange(1, arr.length);

Categories

Resources