I have an owner class, which has an array of owned dogs. It looks like this:
public class Owner {
private String ownerName;
public Dog[] ownedDogs = new Dog[0];
private int dogCount = -1;
public Owner(String ownerName) {
this.ownerName = ownerName;
}
public String getName(){
return ownerName;
}
public void assignDog(Dog d) {
Dog[] newOwnedDogs = new Dog[ownedDogs.length + 1];
for (int i = 0; i < ownedDogs.length; i++) {
newOwnedDogs[i] = ownedDogs[i];
}
ownedDogs = newOwnedDogs;
this.ownedDogs[++dogCount] = d;
makeOwner(this, d);
}
private void makeOwner(Owner o, Dog d) {
if(d.owner !=o) {
d.owner = o;
}
}
public boolean ownerOfDog(Dog d){
if (d.getOwner() == this){
return true;
} else {
return false;
}
}
public String toString(){
return "Name: " + ownerName;
}
And the dog class looks like this:
public class Dog{
private String name;
private String breed;
private int age;
private int weight;
private double tailLength;
public Owner owner;
public Dog(String name, String breed, int age, int weight) {
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public String getBreed() {
return breed;
}
public void increaseAge() {
age++;
}
public int getAge() {
return age;
}
public int getWeight() {
return weight;
}
public double getTailLength() {
if (breed.equalsIgnoreCase("dachshund") || breed.equalsIgnoreCase("tax")) {
return 3.7;
} else {
return weight * (age / 10.0);
}
}
public Owner getOwner(){
return owner;
}
public void setOwner(Owner o) {
if(this.owner != o) {
this.owner = o;
o.assignDog(this);
}
}
public String toString() {
return "Name: " + name + " Breed: " + breed + " Age: " + age + " Weight: " + weight + " Tail length: " + getTailLength() + " owned by: " + owner;
}
}
And I am trying to create a method to remove a dog from the array, this is what i currently have:
public void removeDog () {
System.out.println("Enter the name of the dog?> ");
String name = input.nextLine();
Owner o = findOwner(name);
Dog d = findDog(name);
if(d == null) {
System.out.println("Error: no such dog");
} else {
//Code to remove dog from o.ownedDogs
}
System.out.println(name + " is removed from the register");
}
Is there a good way to remove objects from an array without manually entering the index of the element? I have seen examples using other data types, but I am a beginner in java, so I am having trouble applying it here.
Dog[]to store the dogs owned by an owner? I think with a different data structure like a Map everything would become way easier.for (int i = 0; i < ownedDogs.length; i++) {if(d == ownedDogs[i]) ownedDogs[i] = null;}ArrayListexist. Those classes implement methods, likeremove(...)to alter the items in an Array. Trying to implement a remove method in an Array is reinventing the wheel.