Is there any pre-defined method to swap two elements? - java

If we have to swap two elements in java then we can swap them using a temporary variable.
int temp=a;
a=b;
b=temp;
Also, we can do it by using different ways also but is there any predefined method like C++ that have std::swap()?
In the collection, we have swap() but it only works for the list.

No, there is no pre-defined function that swaps two elements. And for good reason. Java is always pass-by-value. Not like C++, where you can choose whether to give the value or the reference of the variable to the function.
If you want to read more about pass-by-value / pass-by-reference, this answer covers pretty much everything.

No, there is no way to do that without using a temporary variable.
Even C++ implementation of std::swap() uses a temporary variable inside, see here.
If you really want to you can wrap this code in a method and just call it.
This is just for fun but if you really want to swap integers, you can do it like so:
int a = 100;
int b = 25;
a = a + b;
b = a - b;
a = a - b;

Related

Array of objects, difference between Java and C++

I am new to C++ and I am porting over a Java project to C++.
Consider the following Java code, where Piece is a class representing a chess piece:
Piece[][] myPieces = new Piece[8][8];
It creates an array where all the entries are null.
How can I achieve the same thing in C++? I tried:
Piece* myPieces = new Piece[8][8];
But this will create an array with all the entries initialized with the default constructor.
Thanks
Edit: I want the C++ code to be efficient/elegant and I do not care nor wnant to copy paste from Java to C++. I am happy to heavily modify the code structure if needed.
Edit 2: The code is for chess programm, the size of the array will never change and performance is critical.
The simplest way to declare an 8x8 array of optional objects in C++ is like so:
boost::optional<Piece> myPieces[8][8];
The boost::optional type represents an optional object (like your nullable references in Java) that doesn't have all the pitfalls of using pointer types. It should be available as part of the standard library in the next few years.
You may prefer to use the std::array type, which is an encapsulation of fixed-size arrays that allows them to be treated as first-class citizens and also provides a nicer interface:
std::array<std::array<boost::optional<Piece>, 8>, 8> myPieces;
If you want to be able to resize your arrays at run-time, consider std::vector instead.
As you want it performant, and right for C++ instead of a dumb translation, how about this:
Use a size-1 POD-type for piece.
Add all the convenience-methods you might want to it:
struct Piece {
unsigned char value;
constexpr Piece() : value() {}
constexpr operator bool() const {return !value;}
constexpr bool empty() const {return *this;};
constexpr bool black() const {return value&0x80;}
constexpr bool white() const {return value && !black();}
constexpr unsigned piece() const {return value & 0x7f;}
};
Now that would be an equivalent raw array:
Piece board[8][8];
Or use std::array:
#include <array>
std::array<std::array<Piece, 8>, 8> board;
The answer depends, because contrary to Java, in C++ you have different ownership semantics and object lifetime management (the two go hand in hand).
If you want to model objects similar to java, you would write:
using PiecePtr = std::shared_ptr<Piece>;
std::array<std::array<PiecePtr, 8>, 8> Pieces;
The shared_ptr has similar semantics to a java object (pass it around wherever and it's lifetime is guaranteed as long as there are references to it).
If you want to model observed objects (i.e. the array doesn't own them), you should write:
using PiecePtr = Piece*;
std::array<std::array<PiecePtr, 8>, 8> Pieces;
This ensures that when the Pieces object gets destroyed, the actual pieces themselves remain in memory.
If you want to model unique objects, owned by the Pieces array, you should use:
using PiecePtr = std::unique_ptr<Piece>;
std::array<std::array<PiecePtr, 8>, 8> Pieces;
This ensures that when the Pieces object gets destroyed, the actual pieces themselves get destroyed as well.
In C++ you'd do something like:
std::vector<std::vector<std::unique_ptr<Pieces>>> myPieces;
Semantically equivalent would be:
Piece* myPieces[8][8]
as java only knows objects on the heap, pointers.
As Piece probably is not a final class, but has King, Queen, this is the way to go.
In c++, newly created object (even in array) is created with default constructor. That's one of the important differences with java. If you want to call constructors individually, just use vector of vectors and add each one of them.
I have no experience with java but I believe from what I got that this could be a good replacement in C++:
std::array<std::array<unique_ptr<foo>, 8>, 8> arr = {};
if(arr[2][3].get() == nullptr) // Can check for null elements
std::cout << "this is null";
arr[3][4].reset(new foo()); // Initialize an element
smart pointer avoids memory leaks
std::array provides performances comparable to a normal C array
aggregate initialization provides each pointer a null value
fixed size as the java array
So you want to make a Chess engine and performance is critical. There are several online tutorials for this. Speed is important for a Chess AI so it can consider more moves per second, but you may need to sacrifice elegance for that.
You can either store the piece values in the board array directly, or store the pieces in a separate backing array and create the board as pointers to these pieces. There are some advantages to the second approach which I can't remember right now.
std::array<std::array<Peice *, 8>, 8> Board;
std::array<Piece, 32> Pieces;
You can represent an empty cell as a null pointer.
If you want everything in the same array, you can simply use
std::array<std::array<Peice, 8>, 8> Board;
But you will need to create a "dummy" piece value to represent an empty cell.
Note there is no dynamic memory allocation and the data is compact in memory so better cache performance.
Piece could be an enum or a struct with some useful getter functions, such as IsWhite.
In C++, you have to declare as:
Piece *** myPieces;
then, allocate as:
myPieces = new Piece **[8];
then,
for (int i = 0; i < 8; i++) {
myPieces[i] = new Piece *;
}
Now, if you do,
myPieces[0][0] = new Piece(); // C++, calls default constructor of Piece
In Java,
Piece[][] myPieces;
myPieces = new Piece[8][8];
now, if you do,
myPieces[0][0] = new Piece(); // Java, calls default constructor of Piece
Since you have 8x8 known already, you may also declare as (in C++):
Piece * myPieces[8][8]; // 64 pointers preallocated as 8 rows, 8 cols
then,
Now, if you do,
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
myPieces[i][j] = new Piece(); // or new Pawn or new Knight etc, subclass of Piece
}}
or allocate as needed e.g.
myPieces[0][0] = new Piece(); // or new Pawn or new Knight etc, subclass of Piece

Is there a way to have the equivalent of a struct in Java 1.4?

Using the common example of a Point (x, y) object, is there a way to have it as a struct in Java 1.4? The advantage would be that there would not be a separate memory allocation for the Point object because the struct would be part of the containing object. But it would still have member functions to access it.
I'm 98% certain the answer is no but hope springs eternal...
what/why:
In our code we have 100,000+ objects (about 12 - 14% of the total memory footprint) that is an int and a boolean. If that was a C# struct inside the object, it would reduce the number of objects. And... we are looking at making it just an int where 0x40000000 is the boolean value. But handling that is a lot easier if we have member methods for that int and it's treated as a struct.
There is no struct equivalent on Java now, although I believe that they have been hinted for future versions. Still have a look at the flyweight pattern, might be what you are looking for http://en.wikipedia.org/wiki/Flyweight_pattern
No, you have to use Objects for general "structs".
However for simple data structures like pairs of ints, you can use a bit of trickery in order to save memory and increase speed.
int a = 9;
int b = 10;
long pair = (a << 32)|b;
This packs the 32 bits of a and b into a long. Here's how you extract them:
a = (int)(pair >> 32);
b = (int)pair;
An addition to tskuzzy's answer: another possibility would be to lift the int x and int y fields from the Point class into any classes that need to store point values.
Edit in response to comments:
One thing you could do is to have each class that needs to store a single point value extend a Point class. There would be no logical is-a relationship, but it gives you access to Point objects through a single interface. This wouldn't work (I don't think) for any classes that need to store multiple point values, though.

Is it possible to swap two variables in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it possible to write swap method in Java?
Given two values x and y, I want to pass them into another function, swap their value and view the result. Is this possible in Java?
Not with primitive types (int, long, char, etc). Java passes stuff by value, which means the variable your function gets passed is a copy of the original, and any changes you make to the copy won't affect the original.
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
// a and b are copies of the original values.
// The changes we made here won't be visible to the caller.
}
Now, objects are a bit different, in that the "value" of an object variable is actually a reference to an object -- and copying the reference makes it point at the exact same object.
class IntHolder { public int value = 0; }
void swap(IntHolder a, IntHolder b)
{
// Although a and b are copies, they are copies *of a reference*.
// That means they point at the same object as in the caller,
// and changes made to the object will be visible in both places.
int temp = a.value;
a.value = b.value;
b.value = temp;
}
Limitation being, you still can't modify the values of a or b themselves (that is, you can't point them at different objects) in any way that the caller can see. But you can swap the contents of the objects they refer to.
BTW, the above is rather hideous from an OOP perspective. It's just an example. Don't do it.
I'm going to be reallllyyyy annoying and pedantic here because the word "value" has a very specific meaning in Java, which people often don't often understand, especially when the variables hold references to objects.
I am going to assume the question asks for this behavior:
x = initialValueForX;
y = initialValueForY;
swap(x, y);
// x now holds initialValueForY;
// y now holds initialValueForX;
This is not possible because Java passes all arguments to methods by value. You can never change the actual value stored inside of x and y this way.
You can, however, if x and y hold references to objects, change the properties of the two objects in such a way as to make the printed values look like each other's initial values:
x = initialValueForX;
y = initialValueForY;
swap(x, y);
System.out.println(x); prints what looks like initialValueForY
System.out.println(y); prints what looks like initialValueForX
This works if your understanding of value is what the object looks like, rather than what the identity of an object is. Usually, that is acceptable.
(Was going to give a good example here, but cHao already did. Plus others pointed out that this was a duplicate question anyway.)

Java - Efficient way to access an array

it's been some time since I last coded in Java, but I need a little hint here.
We have a simple function - note that this is C:
void update(double *source, double *target, int n) {
for(int i = 0; i < n; ++i)
target[i] = source[i] * i; // well, actually a bit more complicated, just some kind of calculation
}
So, now I need to recode this function in Java - efficiently. My problems are:
Java has of course no pointers, so how can I pass the arrays efficiently without having large amounts of memory copy operations due to call by value
Which data structure is the best to store the arrays
Note that source and target are large arrays, storing up to 1 million elements
In Java it's almost the same thing:
static void update(double[] source, double[] target, int n)
{
for (int i = 0; i < n; i++)
target[i] = source[i] * i;
}
You don't copy any memory. When you pass an array into this function, it's passing a reference to an array by value.
In general, Java passes function arguments by value. But in the case of arrays and user defined classes, the objects you're dealing with are always reference types. So function calls on classes and arrays are always passing the class/array reference by value.
So if you have a class that looks like:
class Foo
{
int[] A; // For arguments say let's say this contains 1 million items always
}
and you have a function that you can call on it:
static void Bar(Foo f)
{
....
}
It only passes the reference to the Foo, it doesn't make a copy of the data at all.
Arrays are passed by reference, (the value of the reference is passed). So there won't be any new copy of array.
Code will be quite similar:
void update(double source[], double target[], int n)
{
for (int i = 0; i < n; i++)
target[i] = source[i] * i;
}
What do you mean by 'data structure for array'? Array itself is a data structure. You anyways have to access each element for the type of operation you are trying to do. So array itself is a good data structure I guess. You may wanna look at ArrayList.
As some others have already pointed out by-ref / by-value is a C/C++ thing and not applicable to Java.
Now unless you're doing some real native coding passing these arrays C/C++ to / fro Java:
Given that in C code array is passed as pointer (void update(double *source, double *target, int n)) I assume it's size is dynamic, if so your signature in Java should be void update(List<Double> source, List<Double> target, int n). Let the caller decide if it's an ArrayList or Vector or LinkedList or ...
But if you're into some JNI (passing these arrays C/C++ to / fro Java) then perhaps we need to consider other aspects.
The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.
But, don't be fooled by this, the internal working is pretty complex, and you can actually manipulate the arrays the way you want.
Verbatim from Oracle's java Tutorials:
Reference data type parameters, such as objects, are also passed into
methods by value. This means that when the method returns, the
passed-in reference still references the same object as before.
However, the values of the object's fields can be changed in the
method, if they have the proper access level.
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail.
the code to use is similar and straightforward:
void update(double source[], double target[], int n)
{
for (int i = 0; i < n; i++)
target[i] = source[i] * i;
}
For a better understanding of what I mentioned, have a look at this question: Is Java "pass-by-reference" or "pass-by-value"?
As to your question of data structures, use an Array. Looking at your snippet, it is clear that you need random access, so just stick to good ol' arrays..
Java uses references for arrays (and other objects). The value of the reference, not the array itself, is passed in method calls, with cost similar to C pointers. If you don't need to expand them dynamically, simple arrays are the fastest data structure to use.
Otherwise, consider ArrayList<Double>. But these are much more expensive, in both speed and size, because each double is "boxed" in a Double object.
A third alternative is to use a relevant resizable list class from a library with high-performance primitive collections, like Trove's TDoubleArrayList.
A question you didn't ask, is whether Java will use any relevant SIMD features of your processor for a simple loop like this. And I'm glad you didn't, because I don't know. But I'm fairly confident that if it is smart enough to use them, it will only be for simple arrays.
Java uses call-by-object semantic, so there is no copying.

How do I pass a primitive data type by reference?

How can I pass a primitive type by reference in java? For instance, how do I make an int passed to a method modifiable?
There isn't a way to pass a primitive directly by reference in Java.
A workaround is to instead pass a reference to an instance of a wrapper class, which then contains the primitive as a member field. Such a wrapper class could be extremely simple to write for yourself:
public class IntRef { public int value; }
But how about some pre-built wrapper classes, so we don't have to write our own? OK:
The Apache commons-lang Mutable* classes:
Advantages: Good performance for single threaded use. Completeness.
Disadvantages: Introduces a third-party library dependency. No built-in concurrency controls.
Representative classes: MutableBoolean, MutableByte, MutableDouble, MutableFloat, MutableInt, MutableLong, MutableObject, MutableShort.
The java.util.concurrent.atomic Atomic* classes:
Advantages: Part of the standard Java (1.5+) API. Built-in concurrency controls.
Disadvantages: Small performance hit when used in a single-threaded setting. Missing direct support for some datatypes, e.g. there is no AtomicShort.
Representative classes: AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference.
Note: As user ColinD shows in his answer, AtomicReference can be used to approximate some of the missing classes, e.g. AtomicShort.
Length 1 primitive array
OscarRyz's answer demonstrates using a length 1 array to "wrap" a primitive value.
Advantages: Quick to write. Performant. No 3rd party library necessary.
Disadvantages: A little dirty. No built-in concurrency controls. Results in code that does not (clearly) self-document: is the array in the method signature there so I can pass multiple values? Or is it here as scaffolding for pass-by-reference emulation?
Also see
The answers to StackOverflow question "Mutable boolean field in Java".
My Opinion
In Java, you should strive to use the above approaches sparingly or not at all. In C it is common to use a function's return value to relay a status code (SUCCESS/FAILURE), while a function's actual output is relayed via one or more out-parameters. In Java, it is best to use Exceptions instead of return codes. This frees up method return values to be used for carrying the actual method output -- a design pattern which most Java programmers find to be more natural than out-parameters.
Nothing in java is passed by reference. It's all passed by value.
Edit: Both primitives and object types are passed by value. You can never alter the passed value/reference and expect the originating value/reference to change. Example:
String a;
int b;
doSomething(a, b);
...
public void doSomething(String myA, int myB) {
// whatever I do to "myA" and "myB" here will never ever ever change
// the "a" and "b"
}
The only way to get around this hurdle, regardless of it being a primitive or reference, is to pass a container object, or use the return value.
With a holder:
private class MyStringHolder {
String a;
MyStringHolder(String a) {
this.a = a;
}
}
MyStringHolder holdA = new MyStringHolder("something");
public void doSomething(MyStringHolder holder) {
// alter holder.a here and it changes.
}
With return value
int b = 42;
b = doSomething(b);
public int doSomething(int b) {
return b + 1;
}
Pass an AtomicInteger, AtomicBoolean, etc. instead. There isn't one for every primitive type, but you can use, say, an AtomicReference<Short> if necessary too.
Do note: there should very rarely be a need to do something like this in Java. When you want to do it, I'd recommend rethinking what you're trying to do and seeing if you can't do it some other way (using a method that returns an int, say... what exactly the best thing to do is will vary from situation to situation).
That's not possible in Java, as an alternative you can wrap it in a single element array.
void demo() {
int [] a = { 0 };
increment ( a )
}
void increment( int [] v ) {
v[0]++;
}
But there are always better options.
You can't. But you can return an integer which is a modified value
int i = 0;
i = doSomething(i);
If you are passing in more than one you may wish to create a Data Transfer Object (a class specifically to contain a set of variables which can be passed to classes).
Pass an object that has that value as a field.
That's not possible in Java
One option is to use classes like java.lang.Integer, then you're not passing a primitive at all.
On the other hand, you can just use code like:
int a = 5;
a = func(a);
and have func return the modified value.

Categories

Resources