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

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

问题描述

我是 Java 新手,我正在尝试找到一种方法来存储 C 中的结构等信息.例如,我想让一个程序雇用员工.它将从用户那里获取名字、姓氏和 ID 号并将其存储.然后,用户可以根据条件查看该信息(例如,如果数据库有超过 1 名员工).任何人都可以建议这样做的最佳方法吗?

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?

推荐答案

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

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; }
    }

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

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天全站免登陆