在 arraylist 中创建具有属性的新对象 [英] create new object in arraylist with attributes

查看:33
本文介绍了在 arraylist 中创建具有属性的新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,我开始使用 ArrayLists.我想做的是为学生创建一个 ArrayList.每个学生都有与他们相关的不同属性(name, id).我想弄清楚如何添加具有此属性的新学生对象.这是我所拥有的:

I am new to Java and I am starting to work with ArrayLists. What I am trying to do is create an ArrayList for students. Each student has different attribute associated with them (name, id). I am trying to figure out how to add a new student object with this attributes. Here is what I have:

ArrayList < Student > studentArray;
public Student(String name, int id) {
  this.fname = name;
  this.stId = id;
}
public Stromg getName() {
  return fname;
}
public int getId() {
  return stId;
}
public boolean setName(String name) {
  this.fname = name;
  return true;
}
public boolean setIdNum(int id) {
  this.stId = id;
  return true;
}

推荐答案

您需要的是以下内容:

import java.util.*;

class TestStudent
{
    public static void main(String args[])
    {
        List<Student> StudentList= new ArrayList<Student>();
        Student tempStudent = new Student();
        tempStudent.setName("Rey");
        tempStudent.setIdNum(619);
        StudentList.add(tempStudent);
        System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
    }
}

class Student
{
    private String fname;
    private int stId;

    public String getName()
    {
        return this.fname;
    }

    public int getId()
    {
        return this.stId;
    }

    public boolean setName(String name)
    {
        this.fname = name;
        return true;
    }

    public boolean setIdNum(int id)
    {
        this.stId = id;
        return true;
    }
}

这篇关于在 arraylist 中创建具有属性的新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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