how to swap two Integer wrapper objects - java

How can I swap the contents of two Integer wrappers?
void swap(Integer a,Integer b){
/*We can't use this as it will not reflect in calling program,and i know why
Integer c = a;
a= b;
b = c;
*/
//how can i swap them ? Does Integer has some setValue kind of method?
//if yes
int c = a;
a.setValue(b);
b.setValue(c);
}

You can't, precisely because Integer is immutable (along with the other primitive wrapper types). If you had a mutable wrapper class, it would be fine:
public final class MutableInteger {
{
private int value;
public MutableInteger(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
void swap(MutableInteger a, MutableInteger b) {
int c = a.getValue();
a.setValue(b.getValue());
b.setValue(c);
}
However, due to the lack of the equivalent of setValue in Integer, there's basically no way of doing what you're asking. That's a good thing. It means that for most cases, where we may want to pass an Integer value to another method, we don't need to worry about whether the method will mutate it. Immutability makes it much easier to reason about your code, without having to carefully trace what every method does, just in case it changes your data under your feet.

Wrapper types in Java are immutable hence provide no setter methods. Plus Java works by passing references by value. Can you tell us why you want to swap stuff?

The type java.lang.Integer represents an immutable number that will never change its value. If you want a mutable number, try MutableInt from Apache Commons.
In Java, as opposed to C++, you cannot pass references to arbitrary memory locations, so swapping is impossible in most cases. The closest thing you can get is this:
public static void swap(Integer[] ints, int index1, int index2) {
Integer tmp = ints[index1];
ints[index1] = ints[index2];
ints[index2] = tmp;
}
You can write similar code using a List<T>, but you always need a container (or two) in which you can swap things.

Refer this article to get a clear idea Article
You will get a clear idea about pass by value pass by reference and and its concepts

you can try something like this :
class MyClass{
int a = 10 , b = 20;
public void swap(MyClass obj){
int c;
c = obj.a;
obj.a = obj.b;
obj.b = c;
}
public static void main(String a[]){
MyClass obj = new MyClass();
System.out.println("a : "+obj.a);
System.out.println("b : "+obj.b);
obj.swap(obj);
System.out.println("new a : "+obj.a);
System.out.println("new b : "+obj.b);
}
}

public class NewInteger {
private int a;
private int b;
public int getA() {
return a;
}
public int getB() {
return b;
}
public NewInteger(int a, int b) {
this.a = a;
this.b = b;
}
public void swap(){
int c = this.a;
this.a = this.b;
this.b = c;
}
}
NewInteger obj = new NewInteger(1, 2);
System.out.println(obj.getA());
System.out.println(obj.getB());
obj.swap();
System.out.println(obj.getA());
System.out.println(obj.getB());
output :
1
2
2
1

Related

Is it possible to modify the value of an attribute sent in argument of a function in Java?

I'm working on a calculator and I search how I can optimize my code.
The thing is that I have much code duplication due to if I'm working on the first number of the calculation or the second. So I'm searching if it is possible to modify the value of an attribute sent in argument of a function ? (I think not because I saw nowhere the answer).
Maybe I'm expressing myself badly so here is a code below to explain what I'm talking about:
public class MyClass
{
private static int number1 = 1;
private static int number2 = 2;
public MyClass()
{
changeValueOf(number1, 3);
}
private static void changeValueOf(int number, int value)
{
//Change here the value of the correct field
}
}
First of all, you can modify static variables inside the method:
private static void changeValueOf(int value)
{
number1 = value;
}
But I guess that is not what you a looking for :)
In Java (and in most other languages) primitive data type (int, short, long, etc) passed by value, e.g. the copy of value passes to the method (function).
And reference types (objects, e.g. created with new operator) passed by reference. So, when you modigy the value of reference type (object) you can see the changes in the outer scopes (for example, in method caller).
So, the answer is no - you cannot change the value of int so that the outer scope would see the updated value.
Howewer, you could wrap your int values with some object - and it change the value inside of it:
public class Example {
public static void main(String[] args) {
Example app = new Example();
// Could be static as well
Holder val1 = new Holder(1);
Holder val2 = new Holder(2);
app.changeValue(val1, 7);
System.out.println(val1.value); // 7
}
public void changeValue(Holder holder, int newValue) {
holder.value = newValue;
}
static class Holder {
int value;
Holder(int value) {
this.value = value;
}
}
}
Also, you could create an array with 2 values and update them inside the method, but it's not very good approach IMO
And finally, you could just return updated value and assign it to your variables:
public class Example {
private static int number1 = 2;
private static int number2 = 3;
public static void main(String[] args) {
Example app = new Example();
number1 = app.mul(number1, 7);
number2 = app.mul(number2, 7);
System.out.println(number1); // 14
System.out.println(number2); // 21
}
public int mul(int a, int b) {
return a * b;
}
}
One possibility is to use an array to store your variables, instead of separate variables with numbers affixed. Then you would write number[1] instead of number1 for example. You can pass the array index number around to indicate which variable you are referring to.
public class MyClass
{
private static int[] variables = {1, 2};
public MyClass()
{
// change value of first variable
changeValueOf(0, 3);
// now variable[0] = 3
}
private static void changeValueOf(int number, int value)
{
variables[number] = value;
}
}

Calling methods on objects Java

I'm taking an introduction to java programming course at university and have an exam next week. I'm going through past exam papers am sort of stuck on this question:
Consider the following class X: class X { private boolean a; private int b; ... }
(i) Write a constructor for this class. [2 marks]
(ii) Show how to create an object of this class. [2 marks]
(iii) Add a method out, which returns b if a is true, and -b otherwise. This method must be usable for any client of
this class. [2 marks]
I've included my code below, but what i'm stuck on is in the final part to this question. How does one call a method on a new object (as we haven't been taught that in class)? Or, does the question imply that the method has to be usable with any object, not just the created object?
Sorry for my awful code and dumb question, i'm really struggling with Java.
public class X {
private boolean a;
private int b;
X(final boolean i, final int j) {
a = i;
b = j;
}
static int Out(boolean a, int b) {
if (a == true) {
return b;
}
return -b;
}
public static void main(String[] args) {;
X object1 = new X(true, 5);
System.out.println(Out(object1));
}
}
You're very close to the solution. Simply make a method like this:
public int out() {
if (a) {
return b;
} else {
return -b;
}
}
Then you can call it in your main method like this:
X object1 = new X(true, 5);
System.out.println(object1.out());
NB: remove the semicolon at the end of public static void main(String[] args) {;
I think you were meant to create a non-static method named out, which can be called by the client of the class (any place where you create a new object of type X) using the dot notation
public int out() {
if(a)
return b;
else
return -b;
}
public static void main(String[] args) {
X object1 = new X(true, 5);
int result = object1.out();
System.out.println(result);
}

Reusing same function in different ways

I have got class like this
class Calculate {
int operation(int a, int b){
return Math.max(a,b);
}
int calc(int a, int b){
int x=100+a*b;
int y=a+a*b;
retun operation(x,y);
}
int calc1(int a, int b){
int x=100+a*b;
int y=b+a*b;
return operation(x,y);
}
}
Now I make two objects of this class as
Calculate obj1=new Calculate();
Calculate obj2=new Calculate();
I want function operation of Class calculate to act like returning maximum of two values for obj1, and return minimum of two values for obj2. Can this be done?
I could only think of creation two different classes Calculate1 and Calculate2 and defining operation as maximum in Calculate1 and minimum in Calculate2 and defining rest thing as same as it is. I hope some easier method also exist without defining two classes.
You can pass the operation to the constructor as an IntBinaryOperator, for example:
class Calculate {
private final IntBinaryOperator op;
public Calculate(IntBinaryOperator operator) {
this.op = operator;
}
int operation(int a, int b) {
return op.applyAsInt(a, b);
}
}
Now you can write:
Calculate c1 = new Calculate(Math::max);
Calculate c2 = new Calculate(Math::min);
And adding an operation is easy - say you want the sum instead of min or max:
Calculate c3 = new Calculate((x, y) -> x + y);
You can override the operation method.
If you don't want to create explicit sub-classes, you can do this with anonymous classes :
Calculate obj1=new Calculate();
Calculate obj2=new Calculate() {
int operation(int a, int b){
return Math.min(a,b);
}
};
obj1.operation(a,b) // calculates maximum
obj2.operation(a,b) // calculates minimum
You can use an OOP concept called Inheritance
public abstract class Calculate {
public abstract int operation(int a, int b);
int calc(int a, int b){
int x=100+a*b;
int y=a+a*b;
return operation(x,y);
}
int calc1(int a, int b){
int x=100+a*b;
int y=b+a*b;
return operation(x,y);
}
}
class Obj1 extends Calculate{
#Override
public int operation(int a, int b) {
return Math.min(a, b);
}
}
class Obj2 extends Calculate{
#Override
public int operation(int a, int b) {
return Math.max(a, b);
}
}
Each new class implements it own method of operation.
You can have something like this :
interface Operation
{
int operation(int a,int b);
}
class Calculate
{
Operation operation;
//rest of class
}
you use the class like this :
Calculate obj1=new Calculate();
obj1.operation=(a,b)->Math.max(a,b);
Calculate obj2=new Calculate();
obj2.operation=(a,b)->Math.max(a,b);
A couple of notes :
you can add a constructor that takes Operation to initialize operation variable.
you should probably have a call method in Calculate class and make operation private for better encapsulation
operation is probably better to be final
This solution may not be as straight forward as other languages but it's the best I can have.
Languages that supported functions as first class citizens from the beginning would make that easier because you can have a function variable which you assign,pass,return just like any variable.
In java we have to use interfaces and anonymous classes to support this, the lambda expressions above were added to java 8 so for java 7 we would write the above like this :
Calculate obj1=new Calculate();
obj1.operation=new Operation{
#Override
int operation(int a,int b)
{
return Math.max(a,b);
}
}
//code for obj2
Edit
You can replace Operation with functional interfaces introduced in java 8(specifically IntBinaryOperator).
You can use strategy pattern to achieve your goal.
Basically you want externalize operation to an interface and specify the object that implements the interface (with min or max) in constructor of Calculate.
This approach gives you most flexible solution that is proof to changes of requirements.
You can modify your class as follows:
class Calculate {
private boolean calcMax;
public Calculate(boolean calcMax){
this.calcMax = calcMax;
}
int operation(int a, int b){
return calcMax ? Math.max(a,b) : Math.min(a,b);
}
}
public class Calculate {
public int a=0;
public int b=0;
public int maxVal = 0;
public int minVal = 0;
public Calculate(int a, int b){
this.a=a;
this.b=b;
this.maxVal=Math.max(a,b);
this.minVal = Math.min(a, b);
}
}
Assuming you are finding the mins and max of the same variables...

Setting variable values to be based on other variables

Say we have variables int a = 0; and int c;.
Is it possible to make it so that c is always equal to something like a + 1 without having to redundantly retype c = a + 1 over and over again
Thanks!
No, it is not possible to make one variable track another variable. Usually, this is not desirable either: when a value of one variable is tied to the value of another variable, you should store only one of them, and make the other one a computed property:
int getC() { return a+1; }
A less abstract example is a connected pair of age and date of birth. Rather than storing both of them, one should store date of birth alone, and make a getter method for computing the current age dynamically.
Since you have 2 variables tied in a specific way, consider using custom object to wrap a and c values. Then you can control the object state inside the class logic. You can do something like this:
public class ValuePair {
private final int a;
private final int c;
public ValuePair(int a) {
this.a = a;
this.c = a + 1;
}
public int getA() {
return a;
}
public int getC() {
return c;
}
}
Firstly, The answer is no, you can't do it directly in Java, but you can redesign your int class, There is an example:
public class Test {
public static void main(String[] args) throws IOException {
MyInt myInt1 = new MyInt(1);
KeepIncrementOneInt myInt2 = new KeepIncrementOneInt(myInt1);
System.out.println(myInt2.getI());
myInt1.setI(2);
System.out.println(myInt1.getI());
System.out.println(myInt2.getI());
}
}
class MyInt { //your own int class for keep track of the newest value
private int i = 0;
MyInt(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
class KeepIncrementOneInt { //with MyInt Class to get the newest value
private final MyInt myInt;
KeepIncrementOneInt(MyInt myInt) {
this.myInt = myInt;
}
public int getI() {
return this.myInt.getI() + 1; //get the newest value and increment one.
}
}
Create your own Int class, because we need a reference type to keep track of the newest the value a. like the MutableInt in apache commons.
Create a always increment 1 class with your own Int class as a member.
In getI method, it's always from the reference Int class get the newest value a.

Multiple returns of different data types

I'm completely lost and getting desperate.
I'm working with Netbeans and what I'm trying to do is just have 2 or more variable of different types be sent to one class, be modified at that location, and then all be returned to the starting location along with the modifications they went under.
I can't put them into an array because in this instance I'm using an Integer and a Double and in the actual code I'm using a lot more than just 2 variables.
public class Passing_Objects {
public void main(String[] args) {
int a = 5;
double b = 10;
? = Extra.Carry(a, b);
System.out.println("A = " + a + ", B = " + b);
}
class Extra {
public int a;
public double b;
public Extra(int _a, double _b) {
this.a= _a;
this.b= _b;
return ?;
}
Either what I'm looking for can't be done or my feeble incompetent mind is too stupid to comprehend the solution everyone else is using.
Either way I can't make any progress in my code unless I solve this problem.
Could someone please help me understand what I need to do and would the solution be any different if variables A or B were arrays?
Something like this ?
public class Passing_Objects {
public void main(String[] args) {
int a = 5;
double b = 10;
Extra extra = new Extra(a, b);
System.out.println("A = " + extra.getA() + ", B = " + extra.getB());
}
class Extra {
public int a;
public double b;
public Extra(int a, double b) {
this.a= a;
this.b= b;
}
public int getA(){
return a;
}
public double getB(){
return b;
}
}
}
Edit :
To alter the values after a first initialization, you need setters.
Something like these two methods in your Extra class.
public void setA(int a){
this.a = a;
}
public void setB(double b){
this.b = b;
}
then in your Passing-Objects class, you can set new values by invoking the setter methods.
extra.setA(20);
extra.setB(20d);
Hope it helps.

Categories