So I have an object, lets call it myObject
Here are the constructors to my object
private static class myObject {
public myObject(int argA) {
this.argA = argA;
}
public myObject(int argA, boolean argB) {
this.argA = argA;
this.argB = argB;
}
public myObject(int argA, int argC, int argD) {
this.argA = argA;
this.argC = argC;
this.argD = argD;
}
public myObject(int argA, String argE) {
this.argA = argA;
this.argE = argE;
}
public int argA = 1;
public boolean argB;
public int argC = 4;
public int argD = 5;
public String argE;
Basically I have default values and the constructor overrides these default values when required.
This makes it very clean in the code when I call these constructors I can just
myObject newObject = new myObject(4);
However, an API is giving me a list of arguments to create this object with
List objectParams1 = Arrays.asList(1,3,4)
List objectParams2 = Arrays.asList(1,false)
List objectParams3 = Arrays.asList(1,"tomato")
myObject newObjectWithTheseParameters1 = ?;
myObject newObjectWithTheseParameters2 = ?;
myObject newObjectWithTheseParameters3 = ?;
Creating this object with a list of params is very difficult as it does not know which constructor to use. Is the builder method the way to go with this? However this will make code base much larger as I have to call this constructor ~100 times..
myObject objectA = myObject.builder().withargA(4).withArgB(true).build();
Not claiming this is the correct way but you could set all values in a main constructor, and then call the main constructor from constructors defined with other signatures using the this keyword:
The only thing to really notice here is that I've set some "default" values where no value is provided in the varying constructors.
private static class myObject {
public int argA = 1;
public boolean argB;
public int argC = 4;
public int argD = 5;
public String argE;
public myObject(int argA, boolean argB, int argC, int argD, String argE) {
this.argA = argA;
this.argB = argB;
this.argC = argC;
this.argD = argD;
this.argE = argE;
}
public myObject(int argA) {
this(argA, false, 0, 0, null);
}
public myObject(int argA, boolean argB) {
this(argA, argB, 0, 0, null);
}
public myObject(int argA, int argC, int argD) {
this(argA, false, argC, argD, null);
}
public myObject(int argA, String argE) {
this(argA, false, 0, 0, argE);
}
}
If you're going to add a lot of these types of constructors, you may end up with signature clashes which won't work. Builder is good when you need to specify a bunch of optional parameters that vary + some that are mandatory. Relatively simple to implement as every method returns itself (this), and you just update the fields as necessary, then finally call .build() to create the object.
You only have four cases, so it's quite easy to write a static factory method:
static myObject create(List<?> args) {
int argA = (int) args.get(0);
switch (args.size()) {
case 1:
return new myObject(argA);
case 2:
if (args.get(1) instanceof Boolean) {
return new myObject(argA, (boolean) args.get(1))
}
return new myObject(argA, (String) args.get(1));
case 3:
return new myObject(argA, (int) args.get(1), (int) args.get(2));
default:
throw new IllegalArgumentException();
}
}
Then:
myObject newObjectWithTheseParameters1 = create(objectParams1);
// etc.
This is pretty gross (it can fail in all sorts of ways at runtime, if the list has the wrong number of elements, or elements of the wrong type, or the boxed primitive elements are null), but I don't really see what other choice you have if the parameters come from a List.
An alternative without doing the explicit checking would be to use reflection to obtain a constructor:
Class<?>[] classes =
args.stream()
.map(Object::getClass)
.map(YourClass::unboxedClass)
.toArray(Class<?>[]::new);
where unboxedClass is a method which translates Integer.class and Boolean.class into int.class and boolean.class. Then:
return myObject.getClass().getConstructor(classes).newInstance(args);
(and handle all the checked exceptions).
Create a constructor that takes all arguments (make it private if you want) and call that one from all others. The arguments you don't have will be set to their default values:
private static class MyObject {
private boolean b;
private int a, c, d;
private String e;
private MyObject(int a, boolean b, int c, int d, String e) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
public MyObject(int a, int c, int d) {
this(a, false, c, d, null);
}
public MyObject(int a, boolean b) {
this(a, b, 3, 4, null);
}
public MyObject(int a, String e) {
this(a, false, 3, 4, e);
}
}
There are however a few downsides to this:
It harms readability and can confuse you.
If you want to change the default values for certain arguments, you'll have to remember to change them in every constructor. You can work around this by storing the defaults in static final variables, but still not ideal.
You should also consider naming your variables differently, as a, b, c, d and e or argA, argB, argC, argD, argE don't really convey much information.
You can use the builder pattern here if you wish. This may look ugly and boilerplate-y, but it means you don't need a separate constructor for each case, and it will allow you to chain your builder, since each instance method in Builder returns this. It also doesn't look too bad if you keep the method names short.
You can use it like this (notice that you can leave out c or any other field because the defaults are set in the Builder class):
MyObject object =
new Builder()
.a(4)
.b(true)
.d(0)
.e("56")
.build();
The modified MyObject class:
class MyObject {
public int a;
public boolean b;
public int c;
public int d;
public String e;
public MyObject(int a, boolean b, int c, int d, String e) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
}
The Builder class
class Builder {
public int a = 1;
public boolean b;
public int c = 4;
public int d = 5;
public String e;
public Builder a(int a) {
this.a = a;
return this;
}
public Builder b(boolean b) {
this.b = b;
return this;
}
public Builder c(int c) {
this.c = c;
return this;
}
public Builder d(int d) {
this.d = d;
return this;
}
public Builder e(String e) {
this.e = e;
return this;
}
public MyObject build() {
return new MyObject(a, b, c, d, e);
}
}
Another way to implement the builder, with a Map and casting afterwards. It's typesafe, but the class above with fields is probably better because it doesn't involve unnecessary boxing and unboxing with primitives.
class Builder {
private Map<String, Object> map = new HashMap<>();
{
map.put("a", 1);
map.put("b", false);
map.put("c", 4);
map.put("d", 5);
map.put("e", null);
}
public Builder a(int a) {
map.put("a", a);
return this;
}
public Builder b(boolean b) {
map.put("b", b);
return this;
}
public Builder c(int c) {
map.put("c", c);
return this;
}
public Builder d(int d) {
map.put("d", d);
return this;
}
public Builder e(String e) {
map.put("e", e);
return this;
}
public MyObject build() {
return new MyObject(
(Integer) map.get("a"),
(Boolean) map.get("b"),
(Integer) map.get("c"),
(Integer) map.get("d"),
(String) map.get("e"));
}
}
I created a class and left it on the user to make an instance. The instance has a constructor that requires the user to input values to the instance :-
public class perfo2{
public int c;
public int p;
public int b;
public String n;
perfo2(int c,int p,int b,String n){ //constructor
this.c=c;
this.p=p;
this.b=b;
this.n=n;
}
Now i have a few methods that requires variable from the instance like:-
public int calculate(int c,int p,int b){
int per= (int)((c+p+b/60*100));
return per;
}
public void dis(int c,int p,int b,String n,int per){
System.out.println("Name:"+n);
System.out.println("Chemistry:"+c);
System.out.println("Physics:"+p);
System.out.println("Biology:"+b);
System.out.println("Percentage:"+per+"%");
} }
now i want these methods to actually access the object for it various variables and use them.
I know what arguments i have given to the methods wont be able to that but what will? and also
if i make an object in the code itself i can easily access the variables by
michael.dis(michael.c,michael.p,michael.b,michael.n,michael.calculate(michael.c,michael.p,michael.b));
Just create a object and use it
perfo2 michael = new perfo2(c,p,b,n);
michael.dis(michael.c,michael.p,michael.b,michael.n,michael.calculate(michael.c,michael.p,michael.b));
A bit extra code to my comment, you could use your class like this example. You could probably add the percentage to your class variables but i did not want to mess with your logic
public class Perfo2 {
private int c;
private int p;
private int b;
private String n;
Perfo2(int c, int p, int b, String n) { // constructor
this.c = c;
this.p = p;
this.b = b;
this.n = n;
}
public int calculate(Perfo2 perfo2) {
return (perfo2.c + perfo2.p + perfo2.b / 60 * 100);
}
public void dis(Perfo2 perfo2,int per) {
System.out.println(perfo2);
System.out.println("Percentage:" + per + "%");
}
#Override
public String toString() {
return String.format("Name: %s%nChemistry: %s%nPhysics: %s%nBiology: %s", this.n ,this.c,this.p,this.b);
}
public static void main(String[] args) {
Perfo2 p = new Perfo2(10,6,5,"Mark");
p.dis(p, 70);;
}
}
If I understand you correctly; you want to be able to access the varaibles set in the consructor c, p, b, n. You should be able to do this by creating getters on each of the variables as such:
public class perfo2 {
public int c; // consider making the access modifier for c,p,b & n private
public int p;
public int b;
public String n;
perfo2(int c, int p, int b, String n) { //constructor
this.c = c;
this.p = p;
this.b = b;
this.n = n;
}
public int getC() {
return c;
}
public int getP() {
return p;
}
public int getB() {
return b;
}
public String getN() {
return n;
}
}
// Create the object as such
perfo2 person1 = new perfo2(1,2,3,"my String");
int c = person1.getC();
int p = person1.getP();
int b = person1.getB();
String n = person1.getN();
You may also want to consider making the access modifier for c,p,b & n private; therefore this cannot be accessed direclty from the object. Depedning on use case you could also use person1.c etc
I have developed an app in which I am retrieving data from Firebase with the help of data class. Problem is the data which I am retrieving can be either String or numbers (int or long) or a combination of both. I have declared the variables inside data class as a String type, so it works fine for String data retrieval but the app crashes when I try to retrieve numbers. This is the data class
public class Choices {
private String a, b, c, d;
public Choices() {
}
public Choices(String a, String b, String c, String d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public String getD() {
return d;
}
public void setD(String d) {
this.d = d;
}
}
I Just want to know is there any way through which I can design the data class in such a way that it can handle both String and numerical data.
I have a SourceClass with following parameters as:
class SourceClass{
public Integer a;
public Integer b;
}
And a DestinationClass as:
class DestinationClass {
public Integer a;
public Integer b;
}
And here is my test code:
public static void main(String[] args) {
Mapper mapper = new DozerBeanMapper();
SourceClass src= new SourceClass();
src.a= 1;
src.b= 2;
DestinationClass dest = mapper.map(src, DestinationClass.class);
System.out.println(dest.a + " " + dest.b);
}
The last line of the code is showing as null null, now I have tried by giving the getter/setter as well but didn't worked, I finally got the output by specifying #Mapping annotation giving the name of the variable to map like #Mappinf("a"), but as you see my variable names are same, can't dozermapper do it by itself?Because here it is written that it maps the same named variables automatically.
Ok so first of all either change SourceClass variables to Strings or change src.a and src.b values to be Integers.
Secondly you need to have getters and setters in both SourceClass and DestinationClass because dozer relies on them regardless if the variables are public or private.
The following solution works:
public class SourceClass{
private Integer a;
private Integer b;
public Integer getA(){
return a;
}
public void setA(Integer a){
this.a = a;
}
public Integer getB()
{
return b;
}
public void setB(Integer b){
this.b = b;
}
}
public class DestClass{
private Integer a;
private Integer b;
public Integer getA(){
return a;
}
public void setA(Integer a){
this.a = a;
}
public Integer getB(){
return b;
}
public void setB(Integer b){
this.b = b;
}
}
public static void main(String[] args)
{
Mapper mapper = new DozerBeanMapper();
SourceClass src = new SourceClass();
src.setA(1);
src.setB(2);
DestClass dest = mapper.map(src, DestClass.class);
System.out.println(dest.getA() + " " + dest.getB());
}
I hope this helps.
I'm working on a project and I'm being forced to make a Linked List that holds objects. Linked lists, as in a data structure that holds things like strings or int values (like arrays, vectors)
In each object there are four types of data (string, double, int, long); but I am only interested in the long value.
TL;DR:
So I guess my question is: "How do I get one value (long) from one Object that holds different types of data"?
public class A {
private int a;
private String s;
private double d;
private long l;
// have getters and setters for these
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public long getL() {
return l;
}
public void setL(long l) {
this.l = l;
}
}
now suppose u have a LinkedList as
LinkedList<A> lla = new LinkedList<A>();
and u have added object of A as
A a = new A();
//initialise the state of a
a.setA(2);
a.setS("Hello");
a.setD(4);
a.setL(5l);
add it to linkedlist
lla.add(a);
u can get object of A anytime if u have the reference of LinkedList lla as
A aObj = lla.get(position); // position is the position of object a of A
then do
long lOfA = aObj.getL();