java - Deleting from an Array using object -
if have array ( cannot arraylist
) used store specific things such "dog type", "dog name" , "dog age". create object input these elements. however, if user wants remove whole object ( inputs name, age , age ) can deleting age of dog removed. possible without using arraylist ?
you can in way. no java approach, works , can refactor it.
here have got dog class:
public class dog { private string name; private int age; public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } public static dog[] removebyname(dog[] list, string name) { int counter = 0; dog[] result = new dog[3]; (int = 0; < list.length; i++) { if (!list[i].getname().equals(name)) { result[counter] = list[i]; counter++; } } return result; } }
here can see how use it:
public class notarraylist { public static void main(string[] args) { dog[] dogs = new dog[3]; dog d1 = new dog(); d1.setname("aaa"); d1.setage(1); dog d2 = new dog(); d2.setname("bbb"); d2.setage(1); dog d3 = new dog(); d3.setname("ccc"); d3.setage(1); dogs[0] = d1; dogs[1] = d2; dogs[2] = d3; dog[] res = dog.removebyname(dogs, "aaa"); (dog d : res) { if (d != null) system.out.println(d.getname()); } } }
Comments
Post a Comment