简体   繁体   English

Java数组可存储一个类的多个对象

[英]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 如何将emp.noEmploye,emp.nom,emp.departement放入数组行

Whit an output like [123,superman,4] 像[123,超人,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 . 为您的Employee类编写一个toString函数,它可以执行您希望的任何格式化,然后只需要System.out.println任何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). 原始数据类型将转换为包装的数据类型(即Integer,而不是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. 如果选择执行此操作,请将I提供的toString与Irfy提供的toString结合在一起。

Well, you could use an Object[] for storing objects of different types, but that's not a good idea in general. 好吧,您可以使用Object[]来存储不同类型的对象,但这一般不是一个好主意。 In Java, being a statically typed language, the usual is to have arrays of a single type. 在Java中,作为一种静态类型的语言,通常是使用单一类型的数组。 Maybe you should reconsider the way you intend to structure your program. 也许你应该重新考虑你打算构建程序的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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