Passing Information to a Method or a Constructor
The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.
Parameter Types
You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.
Here's an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):
Arbitrary Number of Arguments
You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, . ), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.
You will most commonly see varargs with the printing methods; for example, this printf method:
allows you to print an arbitrary number of objects. It can be called like this:
or with yet a different number of arguments.
Parameter Names
When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.
The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.
A parameter can have the same name as one of the class's fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin method:
The Circle class has three fields: x , y , and radius . The setOrigin method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword."
Passing Primitive Data Type Arguments
Primitive arguments, such as an int or a double , are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:
Passing Reference Data Type Arguments
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.
For example, consider a method in an arbitrary class that moves Circle objects:
Let the method be invoked with these arguments:
Inside the method, circle initially refers to myCircle . The method changes the x and y coordinates of the object that circle references (that is, myCircle ) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0 . This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.
Массивы
Массивы в Java — это структура данных, которая хранит упорядоченные коллекции фиксированного размера элементов нужного типа. В Java массив используется для хранения коллекции данных, но часто бывает полезно думать о массиве как о совокупности переменных одного типа.
Вместо объявления отдельных переменных, таких как number0, number1, . и number99, Вы объявляете одну переменную массива, например, numbers и используете numbers[0], numbers[1], . и numbers[99], для отображения отдельных переменных.
Данная статья ознакомит Вас как в Java объявить массив переменных, создать и обрабатывать массив с помощью индексированных переменных.
Объявление массива
Чтобы использовать массив в программе, необходимо объявить переменную для ссылки на массив, и Вы должны указать тип массива, который может ссылаться на переменную. Синтаксис для объявления переменной массива:
Примечание: стиль dataType[] arrayRefVar является предпочтительным. Стиль dataType arrayRefVar[] происходит из языка C/C++ и был принят в Java для C/C++-программистов.
Пример
Следующие фрагменты кода примеры использования данного синтаксиса:
Создание массива
В Java создать массив можно с помощью оператора new с помощью следующего синтаксиса:
Вышеуказанное объявление делает две вещи:
- Создает массив, используя new dataType[arraySize];
- Ссылка на недавно созданный массив присваивается переменной arrayRefVar.
Объявление переменной, создание и присвоение переменной ссылки массива могут быть объединены в одном операторе, как показано ниже:
В качестве альтернативы массивы в Java можно создавать следующим образом:
Элементы массива доступны через индекс. Отсчет индексов ведется от 0; то есть они начинают от 0 и до arrayRefVar.length-1.
Пример
Следующий оператор объявляет массив переменных myList, создает массив из 10 элементов типа double и присваивает ссылку myList:
Изображение отображает массив myList. Здесь myList имеет десять значений double и индексы от 0 до 9.
Работа с массивами
При работе с элементами массива, часто используют цикл for или цикл foreach потому, что все элементы имеют одинаковый тип и известный размер.
Пример
Полный пример, показывающий, как создавать, инициализировать и обработать массив:
Получим следующий результат:
Цикл foreach
JDK 1.5 представила новый цикл for, известный как цикл foreach или расширенный цикл for, который позволяет последовательно пройти весь массив без использования индекса переменной.
Пример
Следующий код отображает все элементы в массиве myList:
Получим следующий результат:
Передача массива в метод
Также как можно передать значение примитивного типа в метод, можно также передать массив в метод. Например, следующий метод отображает элементы в int массиве:
Его можно вызвать путем передачи массива. Например, следующий оператор вызывает метод printArray для отображения 3, 1, 2, 6, 4 и 2:
Возврат массива из метода
Метод может также возвращать массив. Например, метод, показанный ниже, возвращает массив, который является реверсирование другого массива:
Методы для массива
Класс java.util.Arrays содержит различные статические методы для поиска, сортировки, сравнения и заполнения элементов массива. Методы перегружаются для всех примитивных типов.
| № | Описание |
| 1 | public static int binarySearch(Object[] a, Object key) Ищет заданный массив объектов (byte, int, double, и т.д.) для указанного значения, используя алгоритм двоичного поиска. Массив должен быть отсортирован до выполнения этого вызова. Это возвращает индекс ключа поиска, если он содержится в списке; в противном случае (-(точка вставки + 1). |
| 2 | public static boolean equals(long[] a, long[] a2) Возвращает значение true, если два указанных массивах равны друг другу. Два массива считаются равными, если оба массива содержат одинаковое количество элементов, и все соответствующие пары элементов в двух массивах равны. Такой же метод может быть использован всеми другими примитивными типами данных (byte, short, int и т.д.). |
| 3 | public static void fill(int[] a, int val) Присваивает определенное значение int к каждому элементу указанного целочисленного массива. Такой же метод может быть использован всеми другими примитивными типами данных (byte, short, int и т.д.). |
| 4 | public static void sort(Object[] a) Этот метод сортировки сортирует указанный массив объектов в порядке возрастания, в соответствии с естественным порядком его элементов. Такой же метод может быть использован всеми другими примитивными типами данных (byte, short, int и т.д.). |
Пример 1: создание, объявление переменных, определение (выделение памяти) и инициализация массива
В качестве примера возьмем тип данных int. Вы же можете использовать любой другой тип данных.
Пример 2: длина массива
Узнать размер массива в Java можно с помощью метода length(). Данный метод позволяет определить размерность массива.
Получим следующий результат:
Пример 3: максимальный элемент массива
Простые способы для того, чтобы найти максимальное число в массиве в Java. Сперва воспользуемся методом Math.max().
Получим следующий результат:
Ещё один пример нахождения максимального числа в массиве в Java. Здесь мы не будем использовать какие-либо методы.
Получим следующий результат:
Пример 4: минимальный элемент массива
Написанный ниже код практически ничем не отличается от кода, описанного в примере 3. Он в точности наоборот, просто здесь мы ищем минимальное число в массиве в Java. В первом способе воспользуемся методом Math.min().
Получим следующий результат:
Ещё один пример нахождения максимального числа в массиве в Java. Здесь мы не будем использовать какие-либо методы.
Получим следующий результат:
Пример 5: сумма массива
В этом примере рассмотрим как получить сумму элементов массива в Java.
Получим следующий результат:
А в этом примере используем улучшенный цикл for, чтобы найти сумму массива.
Получим следующий результат:
Пример 6: вывод массива
В данном примере рассмотрим как вывести массив на экран в Java.
Получим следующий результат:
Пример 7: вывод четных и нечетных элементов массива
В примере показано как вывести четные и нечетных элементы массива в Java.
Получим следующий результат:
Пример 8: вывод элементов массива с четным и нечетным индексом
В примере показано как вывести на экран элементы массива с четным и нечетным индексом.
передать массив в метод Java
Просто передайте его как другую переменную. В Java массивы передаются по ссылке.
Просто удалите скобки из исходного кода.
Переменная массива — это просто указатель, поэтому вы просто передаете его так:
Edit:
Немного больше. Если то, что вы хотите сделать, это создать COPY массива, вам придется передать массив в этот метод, а затем вручную создать там копию (не уверен, что Java имеет что-то вроде Array.CopyOf() ). В противном случае, вы будете проходить вокруг REFERENCE массива, поэтому, если вы измените любые значения элементов в нем, он будет изменен и для других методов.
Важные точки
- вам нужно использовать пакет java.util
- массив может передаваться по ссылке
В инструкции вызова метода
- Не используйте какой-либо объект для передачи массива
- используется только имя массива, не используйте тип данных или скобки массива []
Пример программы
Программа выходных выборок
Существует важная точка массивов, которые часто не учат или не пропускают в классах Java. Когда массивы передаются функции, тогда другой указатель создается в один и тот же массив (тот же указатель никогда не передается). Вы можете манипулировать массивом, используя оба указателя, но как только вы назначаете второй указатель на новый массив в вызываемом методе и возвращаете обратно в функцию void to call, исходный указатель остается неизменным.
Can I pass an array as arguments to a method with variable arguments in Java?
The problem here is that args is treated as Object[] in the method myFormat , and thus is a single argument to String.format , while I’d like every single Object in args to be passed as a new argument. Since String.format is also a method with variable arguments, this should be possible.
If this is not possible, is there a method like String.format(String format, Object[] args) ? In that case I could prepend extraVar to args using a new array and pass it to that method.
5 Answers 5
Yes, a T. is only a syntactic sugar for a T[] .
JLS 8.4.1 Format parameters
The last formal parameter in a list is special; it may be a variable arity parameter, indicated by an elipsis following the type.
If the last formal parameter is a variable arity parameter of type T , it is considered to define a formal parameter of type T[] . The method is then a variable arity method. Otherwise, it is a fixed arity method. Invocations of a variable arity method may contain more actual argument expressions than formal parameters. All the actual argument expressions that do not correspond to the formal parameters preceding the variable arity parameter will be evaluated and the results stored into an array that will be passed to the method invocation.
Here’s an example to illustrate:
And yes, the above main method is valid, because again, String. is just String[] . Also, because arrays are covariant, a String[] is an Object[] , so you can also call ezFormat(args) either way.
See also
Varargs gotchas #1: passing null
How varargs are resolved is quite complicated, and sometimes it does things that may surprise you.
Consider this example:
Due to how varargs are resolved, the last statement invokes with objs = null , which of course would cause NullPointerException with objs.length . If you want to give one null argument to a varargs parameter, you can do either of the following:
Related questions
The following is a sample of some of the questions people have asked when dealing with varargs:
Vararg gotchas #2: adding extra arguments
As you’ve found out, the following doesn’t "work":
Because of the way varargs work, ezFormat actually gets 2 arguments, the first being a String[] , the second being a String . If you’re passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.
Here are some useful helper methods:
Now you can do the following:
Varargs gotchas #3: passing an array of primitives
Varargs only works with reference types. Autoboxing does not apply to array of primitives. The following works: