简体   繁体   中英

Java array to store multiple object of one class

This my class employes

    public class Employe {

public int noEmploye;
public String  nom;
public int departement;
public double salaireBrut;
public double impots;
public double rrgc;
public double assEm;
public double salaireNet;
public double SalaireAnnuel;
public double suplemetaire;

}

This my main

     Employe emp = new Employe();
     emp.noEmploye=123;
     emp.nom= superman;
     emp.departement= 4;

How to put emp.noEmploye,emp.nom,emp.departement in an array row

Whit an output like [123,superman,4]

Thank for helping me

Frank

Write a toString function for your Employee class which does any formatting you wish, and then simply System.out.println any instance of Employee .

If you write for example

public String toString() {
    return "[%d, %s, %d]".format(noEmployee, nom, department);
}

and then you create a Collection of such objects, you will get an output like

[[123, superman, 4], [1234, batman, 5]]

If you MUST place all of your items in an array, you should do it like this:

Object[] items = {item1, item2, ...};

You could think output everything like this:

public String toString(){
    StringBuilder b = new StringBuilder();
    b.append('[');
    for(int i = 0; i < items.length; i++){
        if(i != 0) b.append(", ");
        b.append(items[i]);
    }
    b.append(']');
}

However, this is generally not a good idea. Primitive data types will be converted to wrapped data types (ie Integer, not int). This reduces efficiency. In addition, it's just plain confusing for someone reading your code.

If you want to consider a bunch of numerical values, what you might consider is something like:

private static final int NO_EMPLOYEE_OFFSET = 0, DEPARTMENT_OFFSET = 1, ...;
int[] data;
String field1;
Point field2;
...

This avoids using wrappers for your primitive data types. However, it won't allow you to store all fields in the array.

If you choose to do this, combine the toString I provided with the one provided by Irfy.

Well, you could use an Object[] for storing objects of different types, but that's not a good idea in general. In Java, being a statically typed language, the usual is to have arrays of a single type. Maybe you should reconsider the way you intend to structure your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM