I was making a project in Greenfoot and I made an imaginary number class. In my project I found a need to add (or subtract, or whatever) two imaginary objects together, is there a way to add two objects like that? So this is how it would look in a perfect world:
Imaginary i1 = new Imaginary(1.7,3.14);
Imaginary i2 = new Imaginary(5.3,9.1);
//the class Imaginary has parameters (double real, double imaginary)
Imaginary i3 = i1+i2;
Is that possible?
Is that possible? However, in Java there is no such thing as operator overloading. It would have to be written similar to i3 = i1. add(i2) (where add is a method that does the appropriate logic and creates the new object).
By Using Integer.sum() Method The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator.
The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set.
One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.
What you are describing is called "Operator overloading" and it cannot be accomplished in Java (at least by programmers such as you and me; the developers have free reign to do this and did so with the String class). Instead, you can create an add
method and call that:
Imaginary i3 = i1.add(i2);
Java has no operator overloading.
For example, BigDecimal
would be a lot more popular if you could write a + b
instead of a.add(b)
.
Way 1.
Imaginary i3 = i1.add(i2);
Method:
public static Imaginary add(Imaginary i2)
{
return new Imaginary(real + i2.real, imaginary + i2.imaginary);
}
Way 2.
Imaginary i3 = add(i1, i2)
Method:
public static Imaginary add(Imaginary i1, Imaginary i2)
{
return new Imaginary(i1.real + i2.real, i1.imaginary + i2.imaginary);
}
Operator overloading would have definitely made design more complex than without it, and it might have led to more complex compiler or slows the JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With