- Как передать массив в класс java
- Initialize an Array in Constructor in Java
- Initialize Array in Constructor in Java
- Initialize Array in Constructor With New Values
- Initialize Array in Constructor in Java
- Related Article — Java Array
- Передача массива в конструктор
- ArrayList в Java
- Что хранит ArrayList?
- Конструкторы ArrayList
- Методы ArrayList
- Ссылки на дополнительное чтение
Как передать массив в класс java
Для передачи массива в класс Java , вам необходимо создать переменную типа массива в вашем классе и передать массив в качестве аргумента в конструктор или метод класса.
public class MyClass private int[] myArray; public MyClass(int[] myArray) this.myArray = myArray; > public void printArray() for (int i : myArray) System.out.println(i); > > > // пример использования int[] numbers = 1, 2, 3, 4, 5>; MyClass myObject = new MyClass(numbers); myObject.printArray(); // => [1, 2, 3, 4, 5]
- Здесь мы создаем класс MyClass с переменной экземпляра myArray типа int[]
- Затем мы создаем конструктор, который принимает myArray в качестве аргумента и устанавливает его как значение переменной экземпляра myArray .
- Далее мы определяем метод printArray() , который просто выводит элементы массива на консоль.
- Когда мы создаем объект MyClass , мы передаем массив numbers в качестве аргумента конструктора, что приводит к тому, что значения в numbers будут присвоены myArray .
- Затем мы вызываем метод printArray() , который выводит содержимое myArray на консоль.
Initialize an Array in Constructor in Java
- Initialize Array in Constructor in Java
- Initialize Array in Constructor With New Values
- Initialize Array in Constructor in Java
This tutorial introduces how to initialize an array in constructor in Java and also lists some example codes to understand the topic.
An array is an index-based data structure that is used to store similar types of data. In Java, we can use an array to store primitive and object values. An array is also an object in Java and initialized with default values. For example, 0 for int, 0.0 for float/double, and null for String/object values.
If an array is declared as an instance variable, it gets initialized with default values when the object is called. Let’s see some examples.
Initialize Array in Constructor in Java
Initializing an array in the constructor does not make sense if it is initialized with default values because Java does this implicitly.
In this example, we declared an array in the class and then initialized it within a constructor, So, the array get initialized when the constructor is called. See the example below.
public class SimpleTesting int a[]; public SimpleTesting() a = new int[]0,0,0>; > public static void main(String[] args) SimpleTesting st = new SimpleTesting(); System.out.println("Array Elements"); // Accessing elements for (int i : st.a) System.out.println(i); > > >
We can do the above task without using constructor and see we get the same output for both code examples. We did not mention the initialization value here, but Java does this for us implicitly. See the example below.
public class SimpleTesting int a[] = new int[3]; public static void main(String[] args) SimpleTesting st = new SimpleTesting(); System.out.println("Array Elements"); // Accessing elements for (int i : st.a) System.out.println(i); > > >
Initialize Array in Constructor With New Values
Initialization using the constructor is a good idea if you want to set new values except for default. In this example, we pass other values, and the array gets initialized when the constructor is called. See the example below.
public class SimpleTesting int a[]; public SimpleTesting() a = new int[]5,5,5>; > public static void main(String[] args) SimpleTesting st = new SimpleTesting(); System.out.println("Array Elements"); // Accessing elements for (int i : st.a) System.out.println(i); > > >
Initialize Array in Constructor in Java
We can create an array in constructor as well to avoid the two-step process of declaration and initialization. It will do the task in a single statement. See, in this example, we created an array inside the constructor and accessed it simultaneously to display the array elements. See the example below.
public class SimpleTesting public SimpleTesting() int a[] = 0,0,0>; System.out.println("Array Elements"); // Accessing elements for (int i : a) System.out.println(i); > > public static void main(String[] args) SimpleTesting st = new SimpleTesting(); > >
Related Article — Java Array
Передача массива в конструктор
Создание объекта и передача аргументов в конструктор
Всем привет, такой вопрос что делает следующая строчка : new NewClass(5); Прошу обратить внимание.
Лямбды. Передача в параметры метода ссылки на конструктор
Имеем код: class Dcoder< public static void main(String args)< Pet pet = Cat :: new; .
Передача массива переменных в конструктор
Всем Привет. Изучаю PHP, вопрос такой, у меня много переменных передается в конструктор в классе.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
package belarus; public class belarus1 { private int kol; public void setkol(int kol){ this.kol=kol; } public int getkol(){ return kol; } private area[] areas=new area[6]; public void Displaycap() { for(int i=0;i6;i++){ if(areas[i].getiscap()) System.out.println("Cтолица"+areas[i].getname()); } } public void Displaykol() { System.out.println("Колличество областей"+getkol()); } public void displaysquare(int id){ for(int i=0;i6;i++){ if(areas[i].getid()==id){ System.out.println("Площадь"+areas[i].getname()+" "+areas[i].getsquare()+" км квадратных"); } } } public void displaycap(int id){ for(int i=0;i6;i++){ if(areas[i].getid()==id){ System.out.println("Столица "+areas[i].getname()+" области "+areas[i].getcapital()); } } } public belarus1(int kol,int[] id,boolean[] iscap,int[] square,String[] capital, String[] name){ setkol(kol); for(int i=0;i6;i++){ areas[i].setid(id[i]); areas[i].setiscap(iscap[i]); areas[i].setsquare(square[i]); areas[i].setcapital(capital[i]); areas[i].setname(name[i]); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
package belarus; public class area { private String name; private int square; private String capital; private boolean iscap; private int id; public void setid(int id){ this.id=id; } public void setname(String name) { this.name=name; } public void setsquare(int num) { this.square=num; } public void setcapital(String capital) { this.capital=capital; } public void setiscap(boolean iscap) { this.iscap=iscap; } public int getid(){ return id; } public String getname() { return name; } public int getsquare() { return square; } public String getcapital() { return capital; } public boolean getiscap() { return iscap; } public area(String name,int num,String capital, boolean iscap) { setname(name); setsquare(num); setcapital(capital); setiscap(iscap); } }
Привёл в порядок ваш код, постарайтесь в будущем следовать стандартам иначе никто не захочет его читать
там было несколько ошибок, надеюсь вы их увидите сами
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
import java.util.Arrays; /** * @author mutagen */ public class BelarusMoya { /** * @param args the command line arguments */ public static void main(String[] args) { Belarus bel = new Belarus(6, new int[]{1, 2, 3, 4, 5, 6}, new boolean[]{false, false, false, false, true, false}, new int[]{4012, 5412, 4312, 6421, 4562, 4555}, new String[]{"Брест", "Витебск", "Гомель", "Гродно", "Минск", "Могилев"}, new String[]{"Брестская ", "Витебская", "Гомельская", "Гродненская", "Минская", "Могилевская"}); System.out.println(bel); } static class Area { private String name; private int square; private String capital; private boolean iscap; private int id; public Area(String name, int square, String capital, boolean iscap, int id) { this.name = name; this.square = square; this.capital = capital; this.iscap = iscap; this.id = id; } @Override public String toString() { return "Area + "name=" + name + ", square=" + square + ", capital=" + capital + ", iscap=" + iscap + ", + id + '>'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSquare() { return square; } public void setSquare(int square) { this.square = square; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } public boolean isIscap() { return iscap; } public void setIscap(boolean iscap) { this.iscap = iscap; } public int getId() { return id; } public void setId(int id) { this.id = id; } } static class Belarus { private int kol; private Area[] areas = new Area[6]; public Belarus(int kol, int[] id, boolean[] iscap, int[] square, String[] capital, String[] name) { this.kol = kol; for (int i = 0; i areas.length; i++) { areas[i] = new Area(name[i], square[i], capital[i], iscap[i], id[i]); } } public void displayCap() { for (int i = 0; i areas.length; i++) { if (areas[i].isIscap()) { System.out.println("Cтолица" + areas[i].getName()); } } } public void displayKol() { System.out.println("Количество областей" + kol); } public void displaySquare(int id) { for (int i = 0; i areas.length; i++) { if (areas[i].getId() == id) { System.out.println("Площадь" + areas[i].getName() + " " + areas[i].getSquare() + " км квадратных"); } } } public void displayCap(int id) { for (int i = 0; i areas.length; i++) { if (areas[i].getId() == id) { System.out.println("Столица " + areas[i].getName() + " области " + areas[i].getCapital()); } } } @Override public String toString() { return "Belarus + "kol=" + kol + ", areas=" + Arrays.toString(areas) + '>'; } public int getKol() { return kol; } public void setKol(int kol) { this.kol = kol; } } }
ArrayList в Java
ArrayList — реализация изменяемого массива интерфейса List, часть Collection Framework, который отвечает за список (или динамический массив), расположенный в пакете java.utils. Этот класс реализует все необязательные операции со списком и предоставляет методы управления размером массива, который используется для хранения списка. В основе ArrayList лежит идея динамического массива. А именно, возможность добавлять и удалять элементы, при этом будет увеличиваться или уменьшаться по мере необходимости.
Что хранит ArrayList?
Только ссылочные типы, любые объекты, включая сторонние классы. Строки, потоки вывода, другие коллекции. Для хранения примитивных типов данных используются классы-обертки.
Конструкторы ArrayList
ArrayList list = new ArrayList<>();
ArrayList list2 = new ArrayList<>(list);
ArrayList list2 = new ArrayList<>(10000);
Методы ArrayList
Ниже представлены основные методы ArrayList.
ArrayList list = new ArrayList<>(); list.add("Hello");
ArrayList secondList = new ArrayList<>(); secondList.addAll(list); System.out.println("Первое добавление: " + secondList); secondList.addAll(1, list); System.out.println("Второе добавление в середину: " + secondList);
Первое добавление: [Amigo, Hello] Второе добавление в середину: [Amigo, Amigo, Hello, Hello]
ArrayList copyOfSecondList = (ArrayList) secondList.clone(); secondList.clear(); System.out.println(copyOfSecondList);
System.out.println(copyOfSecondList.contains("Hello")); System.out.println(copyOfSecondList.contains("Check"));
// Первый способ for(int i = 0; i < secondList.size(); i++) < System.out.println(secondList.get(i)); >И цикл for-each: // Второй способ for(String s : secondList)
В классе ArrayList есть метод для обработки каждого элемента, который называется также, forEach. В качестве аргумента передается реализация интерфейса Consumer, в котором нужно переопределить метод accept():
secondList.forEach(new Consumer() < @Override public void accept(String s) < System.out.println(s); >>);
Метод accept принимает в качестве аргумента очередной элемент того типа, который хранит в себе ArrayList. Пример для Integer:
ArrayList integerList = new ArrayList<>(); integerList.forEach(new Consumer() < @Override public void accept(Integer integer) < System.out.println(integer); >>);
String[] array = new String[secondList.size()]; secondList.toArray(array); for(int i = 0; i
Ссылки на дополнительное чтение
- Подробная статья о динамических массивах, а точнее — об ArrayList и LinkedList , которые выполняют их роль в языке Java.
- Статья об удалении элементов из списка ArrayList.
- Лекция о работе с ArrayList в схемах и картинках.