在Java中创建类似数据结构的结构 [英] Creating struct like data structure in Java

查看:198
本文介绍了在Java中创建类似数据结构的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java很新,我试图找出一种在C中存储信息的方式来存储一个struct。例如,我想要一个程序雇用员工。它将从用户获取名字,姓氏和身份证号码,并将其存储。然后,用户可以根据条件查看该信息(例如,如果数据库具有超过1名员工)。可以任何建议最好的方法吗?

解决方案

C中的结构就像Java中的一个类,功能更强大,因为Java中的类可以包含方法,而C ++则可以。你创建一个新的类。例如:

  class Employee {
private String name;
私有int代码;

//构造函数
public Employee(String name,int code){
this.name = name;
this.code = code;
}

// getter
public String getName(){return name; }
public int getCode(){return code; }
// setter

public void setName(String name){this.name = name; }
public void setCode(int code){this.code = code; }
}

当你想创建多个员工时,像C中一样创建数组:

 员工[] arr = new Employee [100]; // new表示创建数组对象
arr [0] = new Employee(Peter,100); // new表示创建一个员工对象
arr [1] = new Employee(Mary,90);


I am new to Java and I am trying to find out a way to store information like a struct in C. Say for example I want to have a program hire employees. It would take from the user a first name, last name, and id number and would store it. The user could then view that information based off a condition (if the database had more than 1 employee for example). Can any suggest the best way for doing this?

解决方案

A struct in C just like a class in Java and much more powerful, because class in Java can contain method, and C++ does. You create a new class. For example :

   class Employee {
       private String name;
       private int code;

   // constructor
   public Employee(String name, int code) {
      this.name = name;
      this.code = code;
   }

       // getter
       public String getName() { return name; }
       public int getCode() { return code; }
       // setter

       public void setName(String name) { this.name = name; }
       public void setCode(int code) { this.code = code; }
    }

And when you want to create multi employees, create array just like in C:

Employee[] arr = new Employee[100];  // new stands for create an array object
arr[0] = new Employee("Peter", 100); // new stands for create an employee object
arr[1] = new Employee("Mary", 90);

这篇关于在Java中创建类似数据结构的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆