java 填充对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15534043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate an object array
提问by Hyman
I'm currently studying Java and not quite sure how to do this.
我目前正在学习 Java,但不太确定如何做到这一点。
At the moment I have an employee class
目前我有一个员工班
public class employee {
private int empID;
private String empName;
private String job;
//constructors;
public employee(){
this.empID = 0;
this.empName = "";
this.job = "";
}
public employee(int empID, String empName, String job){
this.empID = empID;
this.empName = empName;
this. job = job;
}
//gets;
public int getEmpID(){
return this.empID;
}
public String getEmpName(){
return this.empName;
}
public String getJob(){
return this.job;
}
//sets;
public void setEmpID(int empID){
this.empID = empID;
}
public void setEmpName(String empName){
this.empName = empName;
}
public void setJob(String job){
this.job = job;
}
}
}
While in my main I created an object array of type employee with a size of 2 and then just increase the array count while letting the user enter some basic information and then another loop to print all the information entered.
在我的主要内容中,我创建了一个大小为 2 的员工类型的对象数组,然后增加数组计数,同时让用户输入一些基本信息,然后再循环打印所有输入的信息。
import java.util.Scanner;
public class employeeArray {
public static void p(String s) {System.out.println(s);}
public static void main(String args[]){
Scanner k = new Scanner(System.in);
int empID, size=0, x=0;
String empName;
String job;
employee [] employees = new employee[2];
for(size = 0; size < 2; size++)
{
p("Employee "+(size+1));
p("Please enter employee ID number: ");
empID = k.nextInt(); k.nextLine();
p("Please enter your name: ");
empName = k.nextLine();
p("Please enter your job role: ");
job = k.nextLine();
employees[size] = new employee();
employees[size].setEmpID(empID);
employees[size].setEmpName(empName);
employees[size].setJob(job);
}
for(x=0; x<2;x++){
p("Hello employee: "+employees[x].getEmpName()+" your job role is "+employees[x].getJob()+
" your log in ID is 0800"+employees[x].getEmpID());
}
}
}
}
I understand how to populate each instance of the object by input but say i wanted to increase the size from 2 to 20 but already have the first 10 'pre-entered' so then i could display the 10 i currently have but still allowed to enter 10 more.
我了解如何通过输入填充对象的每个实例,但说我想将大小从 2 增加到 20 但已经有前 10 个“预先输入”,这样我就可以显示我目前拥有的 10 个但仍然允许输入还有 10 个。
ps. sorry for my long-winded question, blocks of code and poor/lack of terminology. I'm new to this.
附:对于我冗长的问题、代码块和糟糕/缺乏术语感到抱歉。我是新手。
回答by Hyman
Don't bother using arrays when you need to dynamically resize them unless it's strictly necessary (and even in that case you could just convert through ArrayList.toArray(..)
).
当您需要动态调整数组大小时,不要费心使用数组,除非绝对必要(即使在这种情况下,您也可以直接转换ArrayList.toArray(..)
)。
Use an ArrayList<Employee>
instead thatn an Employee[]
. You won't have to worry about the capacity, you won't have to worry about deleting and moving elements. It would also support generic containers.
使用 anArrayList<Employee>
代替 thatn Employee[]
。您不必担心容量,也不必担心删除和移动元素。它还将支持通用容器。
As a side note: the naming convention of Java suggests to use Capitalized
names for classes.
附带说明:Java 的命名约定建议Capitalized
对类使用名称。
回答by Hot Licks
A Java array (with a small "a" -- a []
object) is fixed size when created. So if you create the array with 10 elements it will always have exactly 10 elements (though some of them may not have non-null values). If you need to increase the size of the array beyond it's currently allocated size then good luck!! .... Er, I mean you must allocate a new, larger array and then copy the contents of the smaller array into it.
Java 数组(带有一个小的“a”——一个[]
对象)在创建时是固定大小的。因此,如果您创建具有 10 个元素的数组,它将始终只有 10 个元素(尽管其中一些可能没有非空值)。如果您需要将数组的大小增加到超出当前分配的大小,那么祝您好运!!....呃,我的意思是你必须分配一个新的更大的数组,然后将较小数组的内容复制到其中。
Copying an array in this fashion is not all that inefficient, but it is awkward and error-prone, so there are several JDK classes (such as java.util.ArrayList) that can hold a variable-length list and manage the ugly stuff for you. (Truth be told, in general these classes keep an internal array and copy it to a larger one when needed, just as you would, so they're no more efficient. But they simplify coding and reduce errors, and that's the important point.)
以这种方式复制数组并不是那么低效,但它很笨拙且容易出错,因此有几个 JDK 类(例如 java.util.ArrayList)可以保存可变长度列表并管理丑陋的东西你。(说实话,通常这些类会保留一个内部数组,并在需要时将其复制到一个更大的数组中,就像您所做的那样,因此它们的效率并不高。但它们简化了编码并减少了错误,这就是重点。 )
回答by Vishal K
First of all change the class name to Employee
instead of employee
. Stick with java naming conventions.
Now You should take advantage of java utility classes instead . for Example ArrayList<Employee>
. ArrayList
implements dynamically resizing array, which lets the user to insert as much amount of data within it without worrying about the current size of the internal array
because ArrayList
is there to take care of it. But before using ArrayList
to store your Employee
objects you need to override equals
method in Employee
because ArrayList
internally uses this method to find out the existence of look a like object in some methods. The equals
method looks as follows within Employee
class:
首先将类名更改为Employee
而不是employee
. 坚持 Java 命名约定。现在您应该改用 java 实用程序类。例如ArrayList<Employee>
。ArrayList
实现动态调整大小的数组,这让用户可以在其中插入尽可能多的数据,而不必担心内部的当前大小,array
因为ArrayList
可以处理它。但是在ArrayList
用于存储Employee
对象之前,您需要覆盖equals
方法,Employee
因为在ArrayList
内部使用此方法来找出某些方法中是否存在类似对象。该equals
方法在Employee
类中如下所示:
@Override
public boolean equals(Object anObject)
{
if (this == anObject)
{
return true;
}
if (anObject instanceof Employee)
{
Employee anotherEmployee = (Employee)anObject;
if ((this.toString()).equals(anotherEmployee.toString()))
{
return true;
}
return false;
}
return false;
}
@Override
public String toString()//Override it so that it could be easier to compare two objects of Employee using toString()
{
return empID+","+empName+","+job;
}
Now , You can use ArrayList
in following way:
现在,您可以通过ArrayList
以下方式使用:
List<Employee> list = new ArrayList<Employee>();
for(size = 0; size < 2; size++)
{
p("Employee "+(size+1));
p("Please enter employee ID number: ");
empID = k.nextInt(); k.nextLine();
p("Please enter your name: ");
empName = k.nextLine();
p("Please enter your job role: ");
job = k.nextLine();
Employee employee = new Employee();
employee.setEmpID(empID);
employee.setEmpName(empName);
employee.setJob(job);
list.add(employee);
}
for(int i = 0 ;i < list.size() ; i++){
Employee employee = list.get(i);
p("Hello employee: "+employee.getEmpName()+" your job role is "+employee.getJob()+
" your log in ID is 0800"+employee.getEmpID());
}
回答by Ozzie
According to you comments you actually don't want a dynamic array but one with a fixed size of 20 and 10 entered in it.
根据你的评论,你实际上不想要一个动态数组,而是一个固定大小为 20 和 10 的数组。
Example:
例子:
int[] intArray = new int[20];
intArray[0] = 1
intArray[1] = 2
intArray[2] = 3
intArray[3] = 4
intArray[4] = 5
intArray[5] = 6
intArray[6] = 7
intArray[7] = 8
intArray[8] = 9
intArray[9] = 10
//now to fill the rest of the slots.
for(int i = 10; i < intArray.length; i++) {
intArray[i] = i + 1;
}
However you'll be the one that's responsible for keeping track what is in the array and what is not and you cant add more than 20 items to the array.
但是,您将负责跟踪数组中的内容和不包含的内容,并且您不能向数组添加超过 20 个项目。
Edit: You edited your post. With the above code you could do what you want. If you really want to dynamically increase your array without using an ArrayList you could use System#arrayCopy
编辑:您编辑了您的帖子。有了上面的代码,你可以做你想做的。如果你真的想在不使用 ArrayList 的情况下动态增加你的数组,你可以使用 System#arrayCopy
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)
It lets you copy your existing array to a new (empty) array with the new size.
它允许您将现有数组复制到具有新大小的新(空)数组。