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();
}
}
Related
I am trying to return 2 values from a Java method but I get these errors. Here is my code:
// Method code
public static int something(){
int number1 = 1;
int number2 = 2;
return number1, number2;
}
// Main method code
public static void main(String[] args) {
something();
System.out.println(number1 + number2);
}
Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at assignment.Main.something(Main.java:86)
at assignment.Main.main(Main.java:53)
Java Result: 1
Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Java does not support multi-value returns. Return an array of values.
// Function code
public static int[] something(){
int number1 = 1;
int number2 = 2;
return new int[] {number1, number2};
}
// Main class code
public static void main(String[] args) {
int result[] = something();
System.out.println(result[0] + result[1]);
}
You could implement a generic Pair if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* #param first the first element
* #param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair:
public Pair<Object, Object> getSomePair();
You can only return one value in Java, so the neatest way is like this:
return new Pair<Integer>(number1, number2);
Here's an updated version of your code:
public class Scratch
{
// Function code
public static Pair<Integer> something() {
int number1 = 1;
int number2 = 2;
return new Pair<Integer>(number1, number2);
}
// Main class code
public static void main(String[] args) {
Pair<Integer> pair = something();
System.out.println(pair.first() + pair.second());
}
}
class Pair<T> {
private final T m_first;
private final T m_second;
public Pair(T first, T second) {
m_first = first;
m_second = second;
}
public T first() {
return m_first;
}
public T second() {
return m_second;
}
}
Here is the really simple and short solution with SimpleEntry:
AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);
String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();
Only uses Java built in functions and it comes with the type safty benefit.
Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pair class.
you have to use collections to return more then one return values
in your case you write your code as
public static List something(){
List<Integer> list = new ArrayList<Integer>();
int number1 = 1;
int number2 = 2;
list.add(number1);
list.add(number2);
return list;
}
// Main class code
public static void main(String[] args) {
something();
List<Integer> numList = something();
}
public class Mulretun
{
public String name;;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]="siva";
ar[1]="dallas";
return ar; //returning two values at once
}
public static void main(String[] args)
{
Mulretun m=new Mulretun();
String ar[] =m.getExample();
int i;
for(i=0;i<ar.length;i++)
System.out.println("return values are: " + ar[i]);
}
}
o/p:
return values are: siva
return values are: dallas
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
public class DiceExample {
public interface Pair<T1, T2> {
T1 getLeft();
T2 getRight();
}
private Pair<Integer, Integer> rollDiceWithReturnType() {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
return new Pair<Integer, Integer>() {
#Override
public Integer getLeft() {
return (int) Math.ceil(dice1);
}
#Override
public Integer getRight() {
return (int) Math.ceil(dice2);
}
};
}
#FunctionalInterface
public interface ResultHandler {
void handleDice(int ceil, int ceil2);
}
private void rollDiceWithResultHandler(ResultHandler resultHandler) {
double dice1 = (Math.random() * 6);
double dice2 = (Math.random() * 6);
resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
}
public static void main(String[] args) {
DiceExample object = new DiceExample();
Pair<Integer, Integer> result = object.rollDiceWithReturnType();
System.out.println("Dice 1: " + result.getLeft());
System.out.println("Dice 2: " + result.getRight());
object.rollDiceWithResultHandler((dice1, dice2) -> {
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
});
}
}
You don't need to create your own class to return two different values. Just use a HashMap like this:
private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
Toy toyWithSpatial = firstValue;
GameLevel levelToyFound = secondValue;
HashMap<Toy,GameLevel> hm=new HashMap<>();
hm.put(toyWithSpatial, levelToyFound);
return hm;
}
private void findStuff()
{
HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
Toy firstValue = hm.keySet().iterator().next();
GameLevel secondValue = hm.get(firstValue);
}
You even have the benefit of type safety.
Return an Array Of Objects
private static Object[] f ()
{
double x =1.0;
int y= 2 ;
return new Object[]{Double.valueOf(x),Integer.valueOf(y)};
}
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
public class pairReturn{
//name your parameters:
public int sth1;
public double sth2;
public pairReturn(int param){
//place the code of your function, e.g.:
sth1=param*5;
sth2=param*10;
}
}
Then simply use the constructor as you would use the function:
pairReturn pR = new pairReturn(15);
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.
public class HelloWorld{
public static void main(String []args){
HelloWorld world = new HelloWorld();
world.run();
}
private class Dog
{
private String name;
public void setName(String s)
{
name = s;
}
public String getName() { return name;}
public Dog(String name)
{
setName(name);
}
}
public void run()
{
Dog newDog = new Dog("John");
nameThatDog(newDog);
System.out.println(newDog.getName());
}
public void nameThatDog(Dog dog)
{
dog.setName("Rutger");
}
}
The result is:
Rutger
You can create a record (available since Java 14) to return the values with type safety, naming and brevity.
public record MyResult(int number1, int number2) {
}
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.number1() + result.number2());
}
First, it would be better if Java had tuples for returning multiple values.
Second, code the simplest possible Pair class, or use an array.
But, if you do need to return a pair, consider what concept it represents (starting with its field names, then class name) - and whether it plays a larger role than you thought, and if it would help your overall design to have an explicit abstraction for it. Maybe it's a code hint...
Please Note: I'm not dogmatically saying it will help, but just to look, to see if it does... or if it does not.
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;
}
}
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();
I want to do a sum for all over a Collection of numbers. But I want to indicate the return number type. For example I want to do the sum of a double collection, but I want to get back an Integer.
I want to have something like this SumAggregator. Here is the code I develop, but I have a Cast problem.
public class SumAggregator<N1 extends Number, N2 extends Number> {
public SumAggregator() {
}
public N2 sum(Collection<? extends N1> list){
Double sum = 0;
for(Number n : list){
sum += n.doubleValue();
}
return (N2) sum;
}
}
If I want to do SumAggregator<Double, Double> I don't have any problem. But if I want to do SumAggregator<Double, Integer>, once I run I get the following exception:
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Any idea of how to solve this?
Not exactly what you wanted but you could do something like:
interface DoubleConverter<N extends Number) {
N2 convert(double d);
}
And add a constructor to your SumAggregator:
private final DoubleConverter<N2> converter;
public SumAggregator(DoubleConverter<N2> converter) {
this.converter = converter;
}
And your method would look like:
public N2 sum(Collection<? extends N1> list){
double sum = 0;
for(Number n : list){
sum += n.doubleValue();
}
return converter.convert(sum);
}
finally, you would create one with:
SumAggregator<Double, Integer> a = new SumAggregator<> (new DoubleConverter<Integer>() {
public Integer convert(double d) { return (int) d; }
});
Finally, you could add some helper methods in the DoubleConverter interface:
DoubleConverter<Integer> INTEGER = new DoubleConverter<Integer>() {
public Integer convert(double d) { return (int) d; }
}
so the calling code can use:
SumAggregator<Double, Integer> a = new SumAggregator<> (DoubleConverter.INTEGER);
This is the solution I choose:
public class SumAggregator<N1 extends Number, N2 extends Number> {
private final NumberConverter<N2> converter;
public SumAggregator(NumberConverter<N2> converter) {
this.converter = converter;
}
public N2 sum(Collection<? extends N1> list){
double sum = 0;
for(Number n : list){
sum += n.doubleValue();
}
return converter.convert(sum);
}
}
And then:
public interface NumberConverter<N2> {
N2 convert(Number d);
NumberConverter<Short> SHORT = new NumberConverter<Short>() {
public Short convert(Number d) {
return d.shortValue();
}
};
NumberConverter<Integer> INTEGER = new NumberConverter<Integer>() {
public Integer convert(Number d) {
return d.intValue();
}
};
NumberConverter<Double> DOUBLE = new NumberConverter<Double>() {
public Double convert(Number d) {
return d.doubleValue();
}
};
NumberConverter<Float> FLOAT = new NumberConverter<Float>() {
public Float convert(Number d) {
return d.floatValue();
}
};
NumberConverter<Long> LONG = new NumberConverter<Long>() {
public Long convert(Number d) {
return d.longValue();
}
};
}
I'm attempting implement the add method mentioned in the Generic sparse matrix addition question
class Matrix<T extends Number>
{
private T add(T left, T right)
{
if (left instanceof Integer)
{
return new Integer(((Integer)left).intValue() + ((Integer)right).intValue());
}
}
The compiler errors with found java.lang.Integer Required T at the line where I return a new Integer. I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number.
The compiler doesn't let you do this because T might be some other class, such as Double.
You know that T is Integer from the instanceof check, but the compiler doesn't.
Java's type system is simply not capable of expressing this. Here is a work around.
Create an interface Numeric that provides the numeric operations you are interested in, and write its implementations for the data types you are interested in.
interface Numeric<N> {
public N add(N n1, N n2);
public N subtract(N n1, N n2);
// etc.
}
class IntNumeric extends Numeric<Integer> {
public static final Numeric<Integer> INSTANCE = new IntNumeric();
private IntNumeric() {
}
public Integer add(Integer a, Integer b) {
return a + b;
}
public Integer subtract(Integer a, Integer b) {
return a - b;
}
// etc.
}
And rewrite your Matrix class constructor to accept this implementation.
class Matrix<N> {
private final Numeric<N> num;
private final List<List<N>> contents;
public Matrix(Numeric<N> num) {
this.num = num;
this.contents = /* Initialization code */;
}
public Matrix<N> add(Matrix<N> that) {
Matrix<N> out = new Matrix<N>(num);
for( ... ) {
for( ... ) {
out.contents.get(i).set(j,
num.add(
this.contents.get(i).get(j),
that.contents.get(i).get(j),
)
);
}
}
return out;
}
}
// Use site
Matrix<Integer> m = new Matrix<Integer>(IntNumeric.INSTANCE);
Hope that helps.
"I'm not sure what I'm missing since T extends Number and Integer is a subclass of Number."
This statement is false. In general if you have:
public class B extends A {
}
public class C extends A {
}
it does not mean that B can be cast to C. So writing something like:
public <T extends A> T method(T arg) {
return (B)arg;
}
and you calling it with B b = (B)method(C); is obviously wrong.
package generics;
public class Box<T> {
public T j,k;
int l;
float f;
#SuppressWarnings("unchecked")
public void add(T j,T k) {
this.j = j;
this.k=k;
if(j.toString().contains("."))
{
this.f=Float.parseFloat(j.toString())+Float.parseFloat(k.toString());
} else{
this.l=Integer.parseInt(j.toString())+Integer.parseInt(k.toString());
}
}
public int getInt() {
return l;
}
public float getFloat() {
return f;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<Float> floatBox = new Box<Float>();
integerBox.add(new Integer(10),new Integer(20));
floatBox.add(new Float(2.2),new Float(3.3));
System.out.printf("Integer Value :%d\n\n", integerBox.getInt());
System.out.printf("float Value :%f\n", floatBox.getFloat());
}
}