Reputation: 42
I'm working on my coursework and came up with this situation. Here's my code.
public static ArrayList<Student> checkPresent(String unitID, String week){
int present = 0;
ArrayList<Student> studentDetails = Student.getStudentDetails();
ArrayList<AttendanceLog> pickedList = AttendanceLog.pickFromAttendanceLog(unitID, week);
for(Student student : studentDetails){
student.setPresent("N");
for(AttendanceLog attendance : pickedList){
if(student.getStudentNo().equals(attendance.getStudentID())){
student.setPresent("Y");
present++;
}
}
}
return studentDetails;
}
I have only returned the ArrayList
but I also want to get the integer value present
. Is it possible? Or how can I take the int value ?
Upvotes: 2
Views: 1954
Reputation: 366
Create class holing the arraylist and the integer.
classname name = new classname();
name.integerValue= integerValue;
name.arraylist= arraylist;
return arraylist;
Upvotes: 1
Reputation: 2121
Yes, you can create a class which holds both an ArrayList as well as an integer
class SomeClass{
ArrayList<Student> aList;
int present;
}
and have your method return an instance of this class
UPDATE:
public static SomeClass checkPresent(String unitID, String week){
int present = 0;
ArrayList<Student> studentDetails = Student.getStudentDetails();
ArrayList<AttendanceLog> pickedList = AttendanceLog.pickFromAttendanceLog(unitID, week);
for(Student student : studentDetails){
student.setPresent("N");
for(AttendanceLog attendance : pickedList){
if(student.getStudentNo().equals(attendance.getStudentID())){
student.setPresent("Y");
present++;
}
}
}
SomeClass someCls = new SomeClass();
someCls.present = present;
someCls.aList = studentDetails;
return someCls;
}
Note that in your example you're obtaining studentDetails statically, so it wouldn't make much sense to code it this way because you can always get the students list by calling Student.getStudentDetails().
Upvotes: 3
Reputation: 3983
I like to create a new type that has the ArrayList and int as members.
class Result {
public final int value;
public final List<> list;
public Result(int val, List<> list) {
this.value = val;
this.list = list;
}
Upvotes: 0
Reputation: 393956
You can only return one thing from a method.
You have to options :
pass the ArrayList as an argument to the method. The caller would instantiate the ArrayList and the method would populate it. Then your method can return the int
you wish to return in addition to the ArrayList
.
Wrap the ArrayList
and int
in some custom class and change your method to return an instance of that class (you can also do that with an Object[]
, but that would be ugly).
Upvotes: 3