Is There a Way to Have an Arraylist Element Equal to a Class Constructor?

Viewed 596

For an assignment on Arraylists, I am required to change the 1D array into an array list, meaning modifying the program from listName.length to listName.size(), etc.

I am having a problem with declaring my array list animals to a class method. I did this: animals.get(x) = new Dog(name, age); but I am getting an error where it says the left-hand side must be a variable. The same error is occurring on new Cat(name, age); and on new Bird(name, age);.

Now, I have tried creating a String variable and assigning to animals.get(x) and then assigning that variable to new Dog(name,age) which also does not work, as it wants me to change new Dog(name, age) to string (meaning change my variable name, lets say String string, to Dog string), and when I do that, I`m back at square one and it asks me to change my variable back to String.

import java.util.ArrayList;
import java.util.Collection;

public class Database { 
 ArrayList<String> animals = new ArrayList<String>(); 
 Database (int s) { 
  animals.size(); 
 }//end of Database(s)

    boolean addAnimal (int type, String name, int age) {
     for (int x = 0; x < animals.size(); x++) {
      if (animals.get(x) == null) {
       if (type == 1) {
        animals.get(x) = new Dog(name, age);      
       }//end of if 
       else if (type == 2) {
        animals.get(x) = new Cat(name, age);  
       }//end of else if
        else {
                              animals.get(x) = new Bird(name, age);
        }//end of else
        return true;    
      }//end of outer if   
     }//end of for loop  
     return false;
    }//end of addAnimal(type, name, age)

 Animal removeAnimal (String name) {
  for (int x = 0; x < animals.size(); x++) {
   if (animals.get(x).equals(null)) {
    // If the spot in the array is null skip this index
   }//end of if
   else if (animals.get(x).equals(name)) {
    String found = animals.get(x); 
    animals.at(x) = null;
    System.out.print(found);
   }//end of else if
  }//end of for loop
  return null;
 }//end of removeAnimal(name)
}//end of class Database

Since I am modifying everything to fit array lists, I have to modify the method above as well when the user chooses to add an animal. There are three animals, Dog, Cat, and Bird, all of which have their own classes. Im expecting the error'the left-hand side must be a variable' to disappear, and Ive tried searching ways to fix it, but I can`t seem to find a solution similar to my problem.

EDIT UPDATE

I included the complete code for my Database class (the class that has the methods addAnimal and removeAnimal).

4 Answers

According Java documentation of ArrayList (ArrayList), you should use "add" function in order to insert a new element to the ArrayList, which means your code should look something like this:

boolean addAnimal (int type, String name, int age) {
    for (int x = 0; x < animals.size(); x++) {
        if (animals.get(x) == null) {
            if (type == 1) {
                animals.add(new Dog(name, age));                    
            }//end of if    
            else if (type == 2) {
                animals.add(new Cat(name, age));        
            }//end of else if
                else {
                          animals.add(new Bird(name, age));
                }//end of else
                return true;                
        }//end of outer if          
    }//end of for loop      
    return false;
}//end of addAnimal(type, name, age)

Note: I am assuming that the type of the variable "animals" is ArrayList when T is an interface of abstract class of Animal.

Hope i got the question right, let me know if it wasn't your intention.

EDIT:

Well, since your Dog and Cat classes are implementing Animal interface, the type of the ArayList should be:

ArrayList<Animal> animals = new ArrayList<Animal>();

instead of:

ArrayList<String> animals = new ArrayList<String>();

Now, if your intention is just to add new objects to the ArrayList without any other logic (like removing duplicates), you would like to just check the type of the Object and decide what class you should create and add the ArrayList. Then, the code should look like this:

boolean addAnimal (int type, String name, int age) {
    switch(type){
    case 1:
        animals.add(new Dog(name, age));
        return true;
    case 2:
        animals.add(new Cat(name, age)); 
        return true;
    default:
        animals.add(new Bird(name, age));
        return true;
    }
    return false;
}

Another TIP: I don't know about your overall task, but creating a Bird if the type isn't 1 or 2 might not be a good practice since it basically represents that "If an animal isn't a dog or a cat it must be a bird", which in most cases not a very good logic. So my tip is to give a Bird a certain type as well (like 3) and if the type is not 1, 2 or 3 You can alert that the type dosen't exists or something like that. So i would use the "default" as a default:

boolean addAnimal (int type, String name, int age) {
    switch(type){
    case 1:
        animals.add(new Dog(name, age));
        return true;
    case 2:
        animals.add(new Cat(name, age)); 
        return true;
    case 3:
        animals.add(new Bird(name, age));
        return true;
    default:
        System.out.println("This type does not exists"); // Or some other operation
    }
    return false;
}

EDIT 2:

By the way, since "add" can return boolean value if the addition succeed or not, the code can be more elegant:

boolean addAnimal (int type, String name, int age) {
    switch(type){
        case 1: return animals.add(new Dog(name, age));
        case 2: return animals.add(new Cat(name, age)); 
        case 3: return animals.add(new Bird(name, age));
        default: System.out.println("This type does not exists"); // Or some other operation
    }
    return false;
}

Lets be careful here, ArrayList's size method doesn't work like an array's length:

new Object[10].length; // returns 10

List<Object> list = new ArrayList<>(10);
list.size(); // returns 0

list.addAll(Collections.nCopies(10, null));
list.size(); // returns 10

new ArrayList<>(Collections.nCopies(10, null)).size(); // returns 10

As you can see, ArrayLists don't store nulls by default, instead they simply don't store anything. That means there shouldn't be a need to loop through and finds nulls... You can simply add the value to the list.

boolean addAnimal(int type, String name, int age) {
    if (type == 1) {
        animals.add(new Dog(name, age));
    }
    else if (type == 2) {
        animals.add(new Cat(name, age));
    }
    else {
        animals.add(new Bird(name, age));
    }
    return true; // You can probably make this a void method now
}

P.S. I've seen in the comments your ArrayList is of type String ... Your animals aren't strings, so you can either convert them to strings using new Dog(name, age).toString(), or what I'd recommend is changing your ArrayList to be a common type (ie. ArrayList<Animal> animals or ArrayList<Object> animals).

"=" assigns the value on its right to the variable on its left. in your example you want to assign object to object instead of object to variable (animals.get(x) returns object).

Proper way for edit ArrayList element is (as mentioned @Krzysztof Arłasik) method set(int,Object).

In your example:

boolean addAnimal (int type, String name, int age) {
    for (int x = 0; x < animals.size(); x++) {
        if (animals.get(x) == null) {
            if (type == 1) {
                animals.set(x,new Dog(name, age));                  
            }//end of if    
            else if (type == 2) {
                animals.set(x,new Cat(name, age));      
            }//end of else if
            else {
                      animals.set(x,new Bird(name, age));
            }//end of else
            return true;                
        }//end of outer if          
    }//end of for loop      
    return false;
}//end of addAnimal(type, name, age)

ArrayList has method set, which you should use in your case.

For example:

animals.set(x, new Dog(name, age)); 
Related