【问题标题】:Is there a way to get an arraylist element by its name? [duplicate]有没有办法通过它的名字来获取一个数组列表元素? [复制]
【发布时间】:2017-07-03 22:47:43
【问题描述】:

我用Java写了一个程序,遇到以下问题:

//this is the important part of my class student
public class Student{
    private String name;
    public Student(String name){
        this.name = name;
    }
    //Getter
    public String getName() {
        return name;
    }
}

//this is the other class (could be the main for example)
public class Load {
    private ArrayList<Student> student= new ArrayList<Student>();
    student.add(new Student(name));
}

在课程的后期,我再次需要这些学生。我可以像这样得到它们:

System.out.println(student.get(0));

但我没有学生人数。有没有办法通过学生类中的名称来获取它们?

【问题讨论】:

  • 遍历您的列表,检查 student.getName() 是否等于您的搜索,如果是则返回。由于名称不一定是唯一的,您可能希望返回 List
  • 你可以检查名字是否出现在列表中,student.contains("dfighter3")
  • student.stream().filter(x -&gt; x.equals("name")).findAny().orElse(null)
  • 为什么不使用Map&lt;String, Student&gt;(或者更好的是Guava Multimap&lt;String, Student&gt; 来支持多个同名学生)?
  • 我的名字是独一无二的

标签: java arraylist


【解决方案1】:

您可以创建一个函数,该函数将String 作为输入,搜索student 列表并在找到对象时返回。

public Student findStudentByName(String name) {
    for(Student studentObj : student) {
        if(studentObj.getName().equals(name)) {
            return studentObj;
        }
    }
    return null;
}

【讨论】:

    【解决方案2】:

    在这种情况下,也许您可​​以使用地图来保存该学生列表。然后你应该得到学生的名字。

    Map<String, Student> students = new HashMap<String, Student>();
    Student maryIn = new Student();
    maryIn.setName("Mary");
    students.put(maryIn.getName(), maryIn);
    
    Student maryOut = students.get("Mary");
    

    【讨论】:

      【解决方案3】:

      您可以使用student.size() 获取list 中的元素数量。 此外,您应该尽可能使用接口类型,在您的情况下为List&lt;Student&gt; student = new ArrayList&lt;Student&gt;();

      另外,您的代码中有错字:student.add(new Student(name));

      至于最后一个问题,只需在Load 中使用一个额外的方法,在当前列表中搜索所需的学生姓名:

      public Student searchByName(String targetStudentName) {
          for (Student s : student) {
              if (targetStudentName.equals(s.getName())) {
                  return s;
              }
          }
          return null;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 1970-01-01
        • 2019-09-28
        • 1970-01-01
        • 1970-01-01
        • 2013-10-30
        • 2013-04-17
        • 2010-10-16
        • 1970-01-01
        相关资源
        最近更新 更多