Getting Data (long data) from One Object? - java

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();

Related

Is there a way to refactor these constructors?

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"));
}
}

How can use a variable of a object which is created by the user ?(Java)

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

DRY maxima tracking

Suppose I am importing table entries, where a single entry can be stored in a class:
class Foo {
int i1;
int i2;
double d1;
}
After the import is complete, I will need to have access to the imported values themselves, as well as to their normalized versions. So far, I have implemented this functionality as follows:
class FooWithMaxTracking {
private int i1;
private static int i1_max=0;
public void setI1(int value){
this.i1 = value;
if (value > i1_max) { i1_max = value; }}
public int getI1(){
return i1;}
public double normI1(){
return i1/((double)i1_max);}
private int i2;
private static int i2_max=0;
public void setI2(int value){ <code identical to written above> }
public int getI2(){ ... }
public double normI2(){ ... }
// and another set of similar 2 variables & 3 functions for 'double d1'
}
In this implementation I strongly dislike the fact that I had to write the same code many times (only three in this example, but about ten times in the real project). Is there any way to make the code more DRY ("don't repeat yourself")?
If you do not mind a slight loss of performance, you can put all the maxima in a static Map, define a class that holds a getter, a setter, and a norm methods, and replace the individual variables with instances of that class:
private static Map<String,Object> max = new HashMap<String,Object>();
private static class IntMaxTrack {
private final String key;
private int value;
public IntMaxTrack(String k, int v) {
key = k;
value = v;
max.put(key, value);
}
public int get() { return value; }
public void set(int v) {
int m = ((Integer)max.get(key)).intValue();
value = v;
if (value > m) {
max.put(key, value);
}
}
public double norm() {
int m = ((Integer)max.get(key)).intValue();
return val / ((double)m);
}
}
Make a similar class for double, i.e. DblMaxTrack Now you can replace primitives with instances of these classes, and call their get, set, and norm from the corresponding methods of your class.
What about defining one class with the necessary code, like:
public class Bar {
private int i1;
private static int i1_max = 0;
public void setI1(int value) {
// ...
}
public int getI1() {
// ...
}
public double normI1() {
// ...
}
}
And using it sevearl times, like:
class FooWithMaxTracking {
one = new Bar();
two = new Bar();
three = new BarForDouble();
}

Java consecutive method calls

So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}

How can I initialize a generic variable in Java?

I am trying to write a method in which I need to create a temp variable, sum, of generic type T. However, I'm getting the error "The local variable sum may not have been initialized". How can I initialize a generic variable? I can't set it to 0 or 0.0, and I can't find information anywhere on how to deal with this. Here is the portion of code that I'm working with:
public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException
{
Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize);
T sum, product;
if (rowSize != right.columnSize)
throw new MatrixException("Row size of first matrix must match column size "
+ "of second matrix to multiply");
setup(temp,rowSize,columnSize);
for (int i = 0; i < rowSize; i++){
for (int j = 0; j < right.columnSize; j++) {
product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
sum = arithmetics.add(product, sum);
temp.matrix[i][j] = sum;
}
}
return temp;
}
I'm not sure if this will help clarify, but here is my interface Arithmetics:
public interface Arithmetics<T> {
public T zero();
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And here is one of my classes, DoubleArithmetics, just to show how I'm implementing the interface:
public class DoubleArithmetics implements Arithmetics<Double> {
protected Double value;
public Double zero()
{
return new Double(0);
}
public Double add( Double a, Double b )
{
return new Double(a.doubleValue()+b.doubleValue());
}
public Double subtract (Double a, Double b)
{
return new Double(a.doubleValue()-b.doubleValue());
}
public Double multiply (Double a, Double b)
{
return new Double(a.doubleValue()*b.doubleValue());
}
public Double parseString( String str )
{
return Double.parseDouble(str);
}
public String toString( Double a )
{
return a.toString();
}
}
Just use the zero method that you already have on your interface to initialize sum:
T sum = arithmetics.zero();
For the non-zero initialization, you could also add methods that take long and double values and return the T for them:
public interface Arithmetics<T> {
public T zero();
public T create(long l);
public T create(double d);
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
And then implement them:
public Double create(long l) {
return new Double(l);
}
public Double create(double d) {
return new Double(d);
}
And finally, to use them:
T one = arithmetics.create(1);
Instantiating generics in Java is a bit tricky due to type erasure.
My approach is to pass into your generic class' constructor two items: (1) a java.lang.reflect.Constructor specific to type T; and (2) an Object[] array holding a default value specific to type T.
When you later want to instantiate and initialize a type T, you need to call Constructor.newInstance(Object[]). In the code below, the MyGenericClass class stands in for your generic class (looks like it's called Matrix from your original post).
I got the solution from InstantiationException for newInstance() and Create instance of generic type in Java?
public class MyGenericClass<T>
{
Constructor _constructorForT;
Object[] _initialValueForT;
public MyGenericClass(Constructor constructorForT,
Object[] initialValueForT)
{
_constructorForT = constructorForT;
_initialValueForT = initialValueForT;
}
public void doSomething()
{
T sum = initializeT(_constructorForT, _initialValueForT);
System.out.printf("d = %f\n", sum);
}
#SuppressWarnings("unchecked")
private T initializeT(Constructor constructor, Object[] args)
{
T result = null;
try
{
result = (T) constructor.newInstance(args);
}
catch (java.lang.InstantiationException ex)
{
}
catch (java.lang.IllegalAccessException ex)
{
}
catch (java.lang.reflect.InvocationTargetException ex)
{
}
return result;
}
public static void main(String argv[]) throws Exception
{
Constructor constructor =
Double.class.getConstructor(new Class[]{double.class});
Object[] initialValue = new Object[] { new Double(42.0) };
MyGenericClass<Double> myGenericClass =
new MyGenericClass<Double>(constructor, initialValue);
myGenericClass.doSomething();
}
}

Categories

Resources