How can I call the array function in Java?
Currently it looks like:
public static void WriteLine(Object Array[]) {
for (int I = 0; I < Array.length; ++I) {
Out.println(Array[I]);
}
}
public static void WriteLine(Object Text) {
Out.println(Text);
}
I also tried:
public static <T> void WriteLine(T Array[]) {
for (int I = 0; I < Array.length; ++I) {
Out.println(Array[I]);
}
}
and in my main, I do:
int[] I = new int[]{1, 2, 3, 4, 5};
WriteLine(I);
I also tried:
WriteLine<int[]>(I);
Doesn't work..
It prints:
[I#2f56f920
aka the address of the int Array. How can I call the specific array function explicitly or how can I make the compiler know which one to call automatically (implicitly)?
I'm not used to Java/Generics/Object yet.. Just moved from C++ and used to templates :(
An int is not an Object so an int[] is not an Object[]:
Integer[] I = new Integer[]{1, 2, 3, 4, 5};
WriteLine(I);
Or you should have WriteLine overloaded for all the primitive types:
public static void WriteLine(int Array[]) {
...
public static void WriteLine(long Array[]) {
...
I would go for
System.out.println(Arrays.toString(myArray));
I would name your array something other than "Array," as Java is confusing the Array class with the Object or T generic class. You may want to also consider using StringBuilder, if all you want is to print each element of your array.
public static void write(Object arr[]) {
for (int i = 0; i < arr.length; ++i) {
System.out.println(arr[i]);
}
}
Should be good enough.
If you really want to use StringBuilder, and then print, do this:
public static void write(Object arr[]) {
sb = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
sb.append(arr[i] + " ");
}
System.out.println(sb.toString());
}
array of primitive are subtype of java.lang.Object. Overloading is resolved at compile time and the most specific method is selected which in case is writeLine(Object text).
You have two options to make sure that the right function is called:
1-
Object[] objArray = new Object[] { 1, 2, 3, 4, 5 };
2-
Integer[] integerArray = new Integer[] { 1, 2, 3, 4, 5 };
On a side note, you should follow Java naming conventions. for example method name should be writeLine and the index variable in the loop should be small case
Related
I'm currently trying to find all the multiple values of three in an array. I know hot to do it without using a method, but when I'm trying to invoke the method and retrieve the returned array, it gives me errors and won't work.
public class Scratchpad extends ConsoleProgram
{
public void run()
{
int[] test = {4, 7, 9, 7, 12};
findMultipleOfThree testArr = new findMultipleOfThree[int[] test];
System.out.println(testArr);
}
// Copy and paste your Unit Test method here
public int findMultipleOfThree(int[] arr)
{
int length = arr.length;
int[] result = new int[length];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 3 == 0)
{
result[i] = arr[I];
}
}
return result;
}
}
There are a few problems in your code. I think that in your second instruction of the run method, you were attempting to invoke the findMultipleOfThree method you defined below.
To invoke a method, you simply need to type its name and pass the parameters it's expecting. In your case, the test array to find the elements divisible by 3. Plus, you also need to declare a second array result in order to store the returned array from your method with only the elements divisible by 3.
Ultimately, in your findMultipleOfThree method there was a small typo where you referred to the i variable as I. Java is case-sensitive, so it distinguishes between lower-case and upper-case letters.
I think this is what you were trying to write.
public class Scratchpad extends ConsoleProgram {
public void run() {
int[] test = {4, 7, 9, 7, 12};
int[] result = findMultipleOfThree(test);
System.out.println(Arrays.toString(result));
}
public static int[] findMultipleOfThree(int[] arr) {
int length = arr.length;
int[] result = new int[length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 3 == 0) {
result[i] = arr[i];
}
}
return result;
}
}
It looks like you're mixing up methods and classes. You can't declare an instance of a method, and they aren't types you can use for the type of a variable. If you want to call the method, you'd want to use something like int result = findMultipleOfThree(test); and print the result of that with System.out.println(result);
Hope this helps!
Today, I have a question about the list. I want to put the variables in the array into the another array. For example, if there is a int[] list1 and int[] list2 = {1,2,3,4} and int[] list3 = {5,6,7}, I want to put the variables in list2 and list3 into the list1, making the list1 into {1,2 + 5, 3 + 6, 4 + 7}. Below is the code that I have made:
public int function(int[] parameter) {
int[] intlist;
for (int i = 0; i < intlist.length; i++) {
intlist = addVariable(int[] anotherlist); //the function addVariable(int[] parameter) gets a
//int[] as a paremeter, makes a new int[](which has the same size as the parameter) at the
//inside of the function, add parameter's each and every varibles into the new int[] and
//returns the new int[]. and anotherlist keeps changing in the for statement. This is the
//function that I want to make.
}
return intlist;
}
Next is the code of addVariable:
public static int[] addVariables(int[] intlist) {
int[] intlist2 = new int[intlist.length];
for(int i = 0; i < intlist.length; i++) {
intlist2[i] += intlist[i];
}
return intlist2;
}
So, what I want to do is making the intlist whole, by using for statement and addVariable function. But, the addVariable fuction is not complete, as the two lists can have different size, and the function that I've made didn't consider this. Also, the changes that I've made in the for statement doesn't last, so this is a problem as well. How can I fix this situation? Please help!
This is the code you need
public class Test {
public static void main(String args[]) {
int[] intlist = {1, 2, 3, 4};
int[] anotherlist = {5, 6, 7};
Test.addVariables(intlist, anotherlist);
for (int i : intlist) {
System.out.println(i);
}
}
public static void addVariables(int[] intlist, int[] anotherlist) {
for (int i = intlist.length - 1, j = anotherlist.length - 1; i >= 0 && j >= 0; i--, j--) {
intlist[i] += anotherlist[j];
}
}
}
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
list = newList;
}
}
how come the method does not apply and still get 1 2 3 4 5?
thank you !
This is happening because Java is pass by value. This means that when you pass an argument into a method you are passing the reference to it, not the argument itself. The changes that you make inside the method are resolved but in this case you don't return the modified argument. Try this simple experiment to see what I mean:
public static void main(String[] args) {
int x = 0;
foo(x);
System.out.println(x);
}
public static void foo(int x) {
x = 4;
}
This program will print 0 because the changes are essentially discarded. To return the copied reference try this:
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++) {
newList[i] = list[list.length - 1 - i];
}
return newList;
}
And in your main:
oldList = reverse(oldList);
A much more in depth answer:
Is Java "pass-by-reference" or "pass-by-value"?
There are couple of issues. You can fix it with below two Options:
Option 1:
1) Make a new copy of original array and use it as reference array to reverse
2) In reverse function, update values of array that has been passed in parameter and reverse it using reference array
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
// create a copy of initial array to use it to reverse
int[] newList = Arrays.copyOf(list,list.length);
for (int i = 0; i < list.length; i++)
// update original array and reverse it. Calling method still have reference to this array
list[i] = newList[list.length - 1 - i];
}
}
Console Output:
PS: Here the idea is to ensure the reference of array remains the same. You can do it using another array as reference array or using another local variable and swapping two values inside array or doing XOR between i and n-i-1 variable. There are n number of ways out of which 1 has been shared above.
Option 2:
1) No need to copy the reference of the old array to new array in reverse method
2) Return the new array reference back to the calling method
3) For above point you will also have to change the return type of reverse function
4) Save the new reference of array in a variable in the main method and then print from the same.
Please find my comments below:
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
//save the return list to a variable
int[] newList= reverse(oldList);
for (int i = 0; i < newList.length; i++)
//print the data from new list
System.out.print(newList[i] + " ");
}
// change the return type
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
//remove this line as there is no point of copying old array back to new array
// list = newList;
//retrun newlist reference to the calling method
return newList;
}
}
Console Output:
This is happening because you are altering the new area, and the statement list = newList; does not affect the original list because java is pass by value and you only overwrite the pointer in the reverse function.
Instead you should return the new array and overwrite the old one like:
public class HelloWorld
{
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
oldList = reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
return newList;
}
}
Java is always pass-by-value. What does this mean for object- and array-references? In Java, we handle objects only through references. References live on the stack, the actual objects live on the heap. References store the address where the actual object resides.
If you pass an object to a method, the reference-value (i.e. the address where the object resides) is passed as parameter. For some method foo(Object o) this means: if you re-assign o in foo's body (e.g. through o = new Object();, this change will not be visible outside the method.
To fix you problem, you would either have to do the reversal in-place (i.e. on list directly) or return your newly created array. Here is an implementation of the in-place variant:
public static void reverse(final int[] values) {
final int length = values.length;
for (int i = 0; i < length / 2; ++i) {
final int j = length - i - 1;
swap(values, i, j);
}
}
public static void swap(final int[] values, final int i, final int j) {
int tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
For an implementation of the return-variant, look at one of the other answers since every other answer seems to implement a variant on this.
Some remarks on your code:
Giving an array-parameter the name list is confusing. A list is not the same as an array, the are different datastructures with differen properties.
You should never neglect the optional parentheses around one-line if-, else-, for-,... bodies. This can be the source of nasty bugs and is regarded as bad practice.
You should take a little bit more care wrt. your indentation. Keep in mind that your source code is a means of coummuncation. The more semantics you can transport through simple rules (like indentation), the easier it is to understand your source code.
I have a function called tournamentTreeKSelection which finds the K-th largest element in an array. The function takes three parameters, the array, the same array again and the value of K. The purpose of sending two copies of the array is so that during recursive calls, I can modify one copy of the array and still keep the original array I sent in during that call. Here is the code:
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] toArray(ArrayList<Integer> list) {
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; ++i)
arr[i] = list.get(i);
return arr;
}
public static ArrayList<Integer> toList(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr)
list.add(i);
return list;
}
public static int tournamentKSelection(int[] data, int[] data_copy, int k) {
ArrayList<Integer> winners = new ArrayList<>();
for(int i = 0; i < data.length; i += 2) {
winners.add(max(data[i], data[i + 1]));
}
if(k > 1 && winners.size() == 1) {
for(int i = 0; i < data_copy.length; i++)
if(data_copy[i] == winners.get(0))
data_copy[i] = -1;
return tournamentKSelection(data_copy, data_copy, --k);
}
if(winners.size() % 2 == 1 && winners.size() != 1) winners.add(-1);
if(winners.size() == 1) return winners.get(0);
return tournamentKSelection(toArray(winners), data_copy, k);
}
}
Now I am going to test it :
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,1));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,2));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
This produces the following results:
500 // ok this is the first largest number
10 // ok this is the second largest number
8 // this is the fourth largest number, not the third
Now let me make the call to System.out.println(TournamentTree.tournamentKSelection(arr,arr,3)); alone without the call to k = 1 and k = 2
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
Now this produces the correct result, which is 9. What's going on ? Individually, the result is correct but when I make previous calls to the same function first the subsequent results are wrong.
The only explanation I can think of at the moment is that something in my TournamentTree class is static that shouldn't be.
Any insight ?
I think you should call your function in this way:
System.out.println(TournamentTree.tournamentKSelection(arr.clone(), arr.clone(), 1));
And I recommend also interesting thread about arrays and passing them to function:
Are arrays passed by value or passed by reference in Java?
In the call TournamentTree.tournamentKSelection(arr,arr,3), you are passing in the same array for both args, so even though you are not changing the array through the second argument, you are changing it by the first. Java uses pass by reference, not pass by value. To maintain the original, you have to make a copy and pass in each, like:
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
int[] arr_copy = java.util.Arrays.copyOf(arr, arr.length);
System.out.println(TournamentTree.tournamentKSelection(arr,arr_copy,3));
}
I have no problem calling methods that require String or int inputs. For example:
return stringMethod("Hello World");
return intMethod(1,2,3);
but I'm having an issue with the syntax when calling a method which requires array of ints for the input. The syntax I use to call the method countEvens in the code below is not working.
public class _01_countEvens{
public static void main(String[] args){
return countEvens({2,4,6,7});
}
}
public int countEvens(int[] nums){
int result = 0;
for(int x = 0; x < nums.length; x++){
if(nums[x] % 2 == 0) result++;
}
return result;
}
}
This syntax
{2,4,6,7}
is the array creation syntax and can only be used in array creation expressions
new int[]{2,4,6,7}
Read the official Java tutorial on Arrays here.
Either change your method header to:
public int countEvents(int... nums)
And remove the { and } in the call to countEvents,
Or pass: new int[]{2, 4, 6, 7} as an argument.
Array:
int[] a = {0,1,2,3,4,5};
Double Array:
int[][] a2 = {
{0,1,2}
{3,4,5}
};
From there on, just add arrays inside each array. You shouldn't have to make that many dimensions though.