学习过数组的小伙伴应该了解了一维数组的存储方式,但是对于表格类数据的存储,一维数组的存储就不合适了。本篇文章将介绍两种用Java代码实现表格数据的存储。以下是详情内容。
一、二维数组实现表格数据的存储
import java.util.Arrays;
/**
* 使用Object[][]存储表格信息
* @author Lhk
*
*/
public class Array_Test01 {
public static void main(String args[]){
//一个Object[]数组代表表格的一行数据
//此处的基本数据类型1001,1002,1003本质不是Object对象,Java编译会自动把基本数据类型“自动装箱”成包装类对象
Object[] emp0={1001,"明明",20,"程序员","2021-03-28"};
Object[] emp1={1002,"花花",21,"程序员","2021-02-28"};
Object[] emp2={1002,"小李",19,"程序员","2021-04-01"};
Object[][] emps=new Object[3][];
emps[0]=emp0;
emps[1]=emp1;
emps[2]=emp2;
//遍历数组(可用嵌套循环遍历多维数组),输出表格
for(int i=0;i<emps.length;i++){
System.out.println(Arrays.toString(emps[i]));
}
}
}
二、Javabean和数组存储表格信息
import java.util.Arrays;
/**
* 使用javabean和数组存储表格信息
* @author Lhk
*
*/
public class Array_Test02 {
public static void main(String args[]) {
Emps emp0=new Emps(1001,"明明",20,"程序员","2021-03-28");
Emps emp1=new Emps(1002,"花花",21,"程序员","2021-02-28");
Emps emp2=new Emps(1002,"小李",19,"程序员","2021-04-01");
Emps[] emps={emp0,emp1,emp2};//静态初始化
for(int i=0;i<emps.length;i++){
System.out.println(emps[i].toString());
}
}
}
class Emps {
private int id;
private String name;
private int age;
private String job;
private String hiretime;
public Emps(int id, String name, int age, String job, String hiretime) {
super();
this.id = id;
this.name = name;
this.age = age;
this.job = job;
this.hiretime = hiretime;
}
public Emps() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getHiretime() {
return hiretime;
}
public void setHiretime(String hiretime) {
this.hiretime = hiretime;
}
@Override
public String toString() {
//重写toString()方法可以用get方法来返回属性
return "emps [id=" + getId() + ", name=" + getName() + ", age=" + getAge() + ", job=" + getJob() + ", Hiretime=" + getHiretime() + "]";
}
}
以上就是关于Java中表格数据存储方式的全部内容,希望对大家的学习有所帮助,也希望大家多多支持W3Cschool。