creating array of objects in java

Solutions on MaxInterview for creating array of objects in java by the best coders in the world

showing results for - "creating array of objects in java"
Sophie
19 Sep 2020
1obj array[] = new obj[10];
2
3for (int i = 0; i < array.length; i++) {
4  array[i] = new obj(i);
5}
Thiago
20 Aug 2018
1class Main{
2   public static void main(String args[]){
3     //create array of employee object  
4    Employee[] obj = new Employee[2] ;
5 
6     //create & initialize actual employee objects using constructor
7     obj[0] = new Employee(100,"ABC");
8     obj[1] = new Employee(200,"XYZ");
9 
10     //display the employee object data
11     System.out.println("Employee Object 1:");
12     obj[0].showData();
13     System.out.println("Employee Object 2:");
14     obj[1].showData();
15  }
16}
17//Employee class with empId and name as attributes
18class Employee{
19  int empId;
20  String name;
21  //Employee class constructor
22  Employee(inteid, String n){
23     empId = eid;
24     name = n;
25  }
26public void showData(){
27   System.out.print("EmpId = "+empId + "  " + " Employee Name = "+name);
28   System.out.println();
29 }
30}
Laura
31 Feb 2017
1import java.util.stream.Stream;
2
3class Example {
4  
5  public static void main(String[] args) {
6    int len = 5;  // For example.
7    
8    // Use Stream to initialize array.
9    Foo[] arr = Stream.generate(() -> new Foo(1))  // Lambda can be anything that returns Foo. 
10                      .limit(len)
11                      .toArray(Foo[]::new);
12  }
13  
14  // For example.
15  class Foo {
16    public int bar;
17
18    public Foo(int bar) {
19      this.bar = bar;
20    }
21  }
22}
23
Storm
08 Oct 2020
1//create class
2class enemies {
3   int marks;
4}
5//create object array
6enemies[] enemiesArray = new enemies[7];
7//assign value to object
8enemiesArray[5] = new enemies(95);
Leonie
28 May 2020
1Class obj[]= new Class[array_length]
2
similar questions
queries leading to this page
creating array of objects in java