Adding and Removing Java Object Properties

How can I achieve this in java. I have an object that has properties .

 public class Object { private final Credentials Credentials; private final int PageSize; private final int PageStart; private final int DefaultFilterId; public Object(Credentials Credentials, int PageSize, int PageStart, int DefaultFilterId) { this.Credentials = Credentials; this.PageSize = PageSize; this.PageStart = PageStart; this.DefaultFilterId = DefaultFilterId; } } 

Now I create this object like this

 Object obj = new Object(args); 

At some point, I need the same Object, with new properties added, but removing some .

I am doing something similar in javascript.

 var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; delete myCars[1]; or myCars.splice(1,1); 
+4
source share
4 answers
 public class Object { private Credentials credentials; private int PageSize; private int PageStart; private int DefaultFilterId; public Object(Credentials credentials, int PageSize, int PageStart, int DefaultFilterId) { this.credentials = credentials; this.PageSize = PageSize; this.PageStart = PageStart; this.DefaultFilterId = DefaultFilterId; } // do that for the properties you want to be able to modify public void setCredentials(Credentials newCredentials) { this.credentials = newCredentials; } } 

And you use this:

 object.setCredentials(yourNewCredentials) 

In addition, you should not call your object "Object", this is the base class for all classes in Java.

+1
source

put all instances of your object in the collection, and then you can remove them from the collection.

 List<YourObject> list = new ArrayList<YourObject>(); YourObject obj1 = new YourObject("abc"); list.add(obj1); YourObject obj2 = new YourObject("xyz"); list.add(obj2); 

now both objects are inside the list. later you can use the remove method and remove them.

  list.remove(obj1); 

and just a pointer, its a bad practice to name your class as Object like all java extend classes from java.lang.Object .

+3
source

You cannot do this in java. The best approximation is to use a HashTable or similar.

 Hashtable ht = new Hashtable(); ht.put("key", value); 
+1
source

You can add an ArrayList as a private property for your class. And how to create access functions that allow you to add and delete entries. You cannot do this exactly like in JavaScript.

+1
source

Source: https://habr.com/ru/post/1443614/


All Articles