How do I use the bubblesort method in Java when passing a user-defined class as a parameter?
1970-01-01 00:00:00 UTC
How do I use the bubblesort method in Java when passing a user-defined class as a parameter?
Four answers:
2016-04-07 13:14:41 UTC
What you have there doesn't work. The reason for this is that primitive data types in Java are passed by value, not reference. The int x and int y in the initialize() method are local variables generated for that method. Passing in x and y when you call that method only tells that method what values to use internally, it does not allow it to set the values of external primitive variables. In other words, when initialize() is called, two new ints inside it are created and set to the values of x and y that were passed in, leaving the original x and y alone. So initialize() is actually not doing anything useful whatsoever, and after it completes, x and y in main() are still uninitialized. You might be confused because in C++, you CAN do exactly what you're trying to do here, through passing by reference. In C++, you could have something like this: void initialize(int& x,int& y) { x=0; y=0; } int main() { int x,y; initialize(x,y); } and it would work, because the & signs stand for 'pass by reference', meaning that the initialize() function really IS modifying the original x and y from main(). Java also does this with objects, but it does NOT do this with primitive data types such as int. As far as I know there is no way in Java to initialize a local int outside of the method it is local to. If you wanted, you could create a wrapper object for an int and pass THAT into the initialize() method (which would also have to be modified appropriately), since objects are passed by reference. However, in my experience something like this is hardly ever worthwhile and usually would just make your program slower for no good reason (you might as well just initialize them when you declare them and avoid the cost of the object references, method calls, etc).
anonymous_person_1337
2008-05-21 23:38:50 UTC
You could overload the "<" or ">" operators, so when the items are compared, you can do more complex things like compare multiple pieces of data.
modulo_function
2008-05-21 22:36:09 UTC
You could define an array the same size as the Account array and code as elements the numbers 1 to 26 representing the first letter of the names. Sort that array and use it to rearrange your Account array.
Then again, a better question might be 'Why do you need to use the bubblesort method"?
asourapple100
2008-05-21 23:39:15 UTC
To create an array of user-created objects you do something like this:
//let's say we have a class called Test
Test[] testHolder = new Test[5];
That creates an array of Test objects with length 5.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.