Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I'm unsure how I go about referencing objects to my arraylist.
The class where im declaring the arraylist:
Any help would be much appreciated
First of all name is not static so you can not access it as Student.name only instance of student can access it if it's public.Now, you want to construct the Student than you should pass the name of student in constructor.You can declare getter and setter methods for your Student attributes.
Moreover ArrayList.add can be used to add your Students to your list and you better not add students in constructor use different method to write this scenario.
FOR EXAMPLE :
Student student = new Student("NewStudent");
System.out.println("Name of student :" +student.getName());
studentList.add(student);
Regarding:
public TutorGroup() {
super();
Student student = new Student(Student.name); // this makes no sense
studentList.add(student.Student(name, tmaMark));
}
I'm not sure what you're trying to do with new Student(Student.name) since it isn't clear what this code is trying to do, but regardless, the compiler is right -- it shouldn't exist, and so get rid of it.
Delete this TutorGroup constructor and re-do it. How you re-do it will depend on where your TutorGroup is to get the Student objects. If they're going to be packed into an ArrayList and then passed in, then give TutorGroup's constructor an ArrayList<Student> parameter, and when calling the class, pass in the list. If you will add Students one at a time, then make the constructor simple (or get rid of it), and give the TutorGroup class an addStudent method:
public void addStudent(Student s) {
studentList.add(s);
}
In your TutorGroup constructor your trying to pass the value in the name variable in the Student class which you cant access because 1. The name variable is private so only members of the class have access to it. and 2. It doesn't hold a value yet since that's what your trying to pass into the Student constructor.
What you should do is pass a string literal into your Student constructor like: new Student("Jamie") then it will be saved in the name variable in your Student class, and if you need to access the name later add a public method in your Student class that returns the value in your name variable.
Your code has several issues.
Firstly the Student class should have some getter methods, so that you can access the data from a student object:
public String getName() {
return this.name;
}
public int getTmaMark() {
return this.tmaMark;
}
For creating a student object with the correct data, you have 2 options:
Option A) Create a constructor for Student that takes both values:
public Student(String aName, int aMark)
{
super();
this.name = aName;
this.tmaMark = aMark;
}
Option B) Create setters for your Student class
public void setName(String aName) {
this.name = aName;
}
public void setTmaMark(int aMark) {
this.tmaMark = aMark;
}
You can, of course, implement both options in Student, giving you extra flexibility.
Then, to add a new Student to your ArrayList, you can simply create a student and use the array's add method:
Examples:
ArrayList<Student> studentList = new ArrayList<Student>();
// Create student using constructor
Student studentA = new Student("Alice", 15);
// Create student using setters
Student studentB = new Student();
studentB.setName("Bob");
studentB.setTmaMark(10);
// Add both students to the ArrayList
studentList.add(studentA);
studentList.add(studentB);
Please remeber that for the studentB example, if you added a constructor with arguments to your Student class (Option A) you also need to create an explicit default constructor (without arguments).
Im not sure exactly what you are trying to do. I am going to assume you want to add a student into the ArrayList called student list. The line Student student = new Student(Student.name); is creating a new object of type Student called student but you are not passing into any parameters into the constructor for the student class, but it requires a String which is used as the name. What you want to do (i think) is add a student to your array list. As your ArrayList has type student the method to add student x should be
public void addStudent(Student x)
{
studentList.add(x);
}
Where Student x is passed as a paramater to the addStudent method. To Create a new student with the object name newstu and the name nameOfStu you could do this.
Student newstu = new Student(nameOfStu);
addStudent(newstu);
I hope this helps.
Related
i'm newbie in this world currently i'm learning java and i wanna to know why i can't use multiple this() in a constructor someone can tell me why please?
public class Student {
private String name;
private int age;
public Student(String name) {
System.out.println("Name of Student : " + name);
}
public Student(int age)
{
System.out.println("Age of student = " + age);
}
public Student()
{
this("Alex");
this(22); //Error in this line:Call to 'this()' must be first statement in constructor body
}
public static void main(String[] args){
Student student=new Student();
}
}
Analogy from one newbie java coder to another:
You log into your Starbucks app, looking to place a new order of drinks. (1) If you tap “Buy with one click!” on the frappuccino image, it will create a new order that has a frappuccino in it, finalize the order, and place it all in one go. This is what your first two Student constructors do. (2) Or, you could just click the button, “Start a new order”, and you won’t have anything in your cart yet. The second option is what you have chosen to do in your code. Remember: “new Student();” is ONE new order because there is only ONE new keyword.
If you have ever tried to place an order, you know that you cannot place an order if the order contains nothing. So instead of immediately sending it to your Starbucks location, it gives you a chance to add items to your order. Everything that you want in your order goes in between the parentheses ().When you called “this(“Alex”);”, you were really filling your order with ONE “Alex” drink and then placing it because you closed the parentheses (told the app, “this is what is in my cart for my order”).
When you then called “this(22)”, your code got confused because you were trying to add a 22 drink to an order you already placed. You cannot order a drink and then, 5 minutes later, add another drink to the SAME order.
Suggestion: make a constructor Student(name, age) and call this("Alex", 22) instead.
Alternatively: call this(22) inside Student(String) instead!
The main purpose of using this keyword to call the current class constructor inside other constructor.
you can call the current class constructor in first line of the constructor otherwise you get compile time error.
The reason if you create the object to call the constructor first check they any current class constructor is present or not if it present execute the constructor first and after that, this constructor is executed.
why we cannot use multiple this() in one constructor?. Because inside the constructor you can call one constructor at a time.
I'm basically making a class for each university course where any number of students can apply. I wanted to know how can I have a constructor where it doesn't matter if my number of 'Student' objects is 1 or 15 or more...cause I know there's a way, just can't remember it...
import java.util.ArrayList;
public class Course {
String name;
ArrayList <Student>listofstudents=new ArrayList<>();
int noofStudents;
//The class Student is defined.
Course(String name,Student s1, Student s2){
this.name=name;
listofstudents.add(s1);
listofstudents.add(s2);
//Do I have to do this for every possible number of student?
}
}
As your other answer observes, constructors can have variable arguments just like regular methods can have. However, you should consider just saying no. That is, the students enrolled in a given course are a secondary attribute, and you can put a Course into a valid state without them. Consider, then, not accepting the students via the constructor, but instead having one or more methods to add students to existing Courses. (You might need that anyway.) Then just add the students via that route after initializing the Course.
void addStudent(Student s) {
listofstudents.add(s);
}
void addStudents(Student ... s) {
if (s != null) {
listofstudents.addAll(java.util.Arrays.asList(s));
}
}
You can use varargs. Variable Arguments is a technology that allows you to create methods with an arbitrary number of arguments.
import java.util.ArrayList;
public class Course {
String name;
ArrayList <Student>listofstudents=new ArrayList<>();
int noofStudents;
//The class Student is defined.
Course(String name,Student ... s){
Student [] stds = s;
this.name=name;
//your code
}
}
Varargs are straightforward to use. But there're a few rules we have to keep in mind:
Each method can only have one varargs parameter
The varargs argument must be the last parameter
Every time we use varargs, the Java compiler creates an array to hold the given parameters.
Now you can use the constructor in this way:
new Course("Name");
new Course("Name", new Student());
new Course("Name", new Student(), new Student(), new Student());
it's maybe a newbie question but I think it will be helpful for some beginners.
My question is :
public abstract class Person {
code goes here ....
}
public class Employee extends Person {
code goes here ....
}
What is the difference between those kind of instantiation ?
Person student = new Employee("Dove","Female",0);
and
Employee student = new Employee("Dove","Female",0);
They are essentially the same, but the compiler treats Person student as a Person without any type information from the concrete class Employee
It's basically the same thing, but the difference is that:
1- In the first declaration:
Person student = new Employee("Dove","Female",0);
Here student can't access Employee class specific methods or attributes as it's a Person object which contains an Employee instance.
2- But in the second one:
Employee student = new Employee("Dove","Female",0);
Here student can benefit from both Employee and Person attributes and methods.
Please check Polymorphism Oracle Docs for further reading about polymorphism in Java.
Example:
We can see that in this example, where we use Integer and Object classes:
Integer i1= new Integer(0);
//This will run and execute perfectly
System.out.println(i1.intValue());
Object i2= new Integer(0);
//This will throw an error as `Object` class doesn't have `intValue()` method.
System.out.println(i2.intValue());
This is a live working Demo so you can see that.
Following is difference in both instantiation.
(1)
Person student = new Employee("Dove","Female",0);
In this instantiation student is object of Person class so it can't access Employee class specific methods or attributes.
(2)
Employee student = new Employee("Dove","Female",0);
Here, in second instantiation student can access Employee class specific methods and attributes as well as Person class because it is extending in Employee class.
This is basic difference in this two statements.
I've got two classes, LabClass and Student with students being enrolled in the class and given grades.
I've called Student into LabClass as an ArrayList using the following:
private List<Student> students;
Now, I want to be able to individually allocate grades to each student after they have been enrolled.
I've created a method in the Student class to allocate grades and tried to call upon it in LabClass, but it didn't work.
The code in Student is as follows:
public void grade(int marks){
grades = marks;
}
And I tried to call it within LabClass with the following code:
public void giveGrades(){
for(Student student : students){
student.grade(int marks);
}
}
But I get returned the error ".class expected". What's wrong with my code?
Should I be using the set command of Arrays to change the element's value? If so, how should I write it such that it can take in external values from a parameter? Also, how do I specify which value of the element is being changed?
First let's clarify some concepts here. As other mentioned, this code:
public void giveGrades(){
for(Student student : students){
student.grade(int marks);
}
}
does not work because you must not set the type of the parameter when you're using a method (you do it when declaring it). So the first "fix" here would be:
public void giveGrades(){
for(Student student : students){
student.grade(marks);
}
}
Now the question is: What is marks? It's not defined anywhere. Let's suppose for a moment that we do have it defined and that its value is 3. The previous code assigns 3 as a grade for all the students. That's not very realistic, even if "marks" is an int that we somehow receive as a parameter. We probably want a grade for each student, and that means we need a list. So let's say we want a parameter with the list of grades we want to assign to the students: ArrayList<Integer> grades (you can change it later to Double if you want, but the idea is the same). In this case we need to go through each element in the list of students and assign a element from the list grades. Something like this:
you have a list of students students: <s1, s2, s3, s4>
you have a list of grades grades: <g1, g2, g3, g4>
you eant to assign to each student a grade from the list: s1.grade(g1), s2.grade(g2), s3.grade(g3), s4.grade(g4)
We can achieve that with a for also, but one that allows us to iterat over both lists. A possible way (there are more sofisticated ones):
public void giveGrades(ArrayList<Integer> grades){
for(int i = 0; i < students.size(); i++){
students.get(i).grade(grades.get(i))
}
}
That's from the java perspective. Now, according to your comments you need a external parameter and you mention the use of bluej. In the question How do I enter parameters for an ArrayList in BlueJ? you can get a better idea about how to pass a parameter to your method.
Say below is my bean class:
public class Employee {
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my main class:
import java.util.ArrayList;
public class MainClass {
public static void main(String[] args) {
Employee employee = new Employee();
employee.setName("First name");
ArrayList<Employee> empList = new ArrayList<Employee>();
empList.add(employee);
employee.setName("Last name");
for (Employee emp : empList) {
System.out.println(emp.getName());
}
}
}
When I executed the output is: Last name
My question is:
As I know Java is pass-by-value or rather
pass-by-copy-of-the-variable-value then does the copy of
employee object was saved in the ArrayList or it references the
original object of Employee as the object value is getting changed
to Last name after adding to ArrayList?
Does every Collection behave this way?
A copy of the employee reference was saved in the ArrayList, but since it refers to the same Employee instance, changing the instance later via the employee reference affects the element stored in the ArrayList.
Yes, every Collection behaves this way, since the Collections don't create copies of the instances passed to them, they just store references to those instances.
As I know Java is pass-by-value or rather pass-by-copy-of-the-variable-value then does the copy of employee
object was saved in the ArrayList or it references the original object
of Employee as the object value is getting changed to Last name after
adding to ArrayList?
The reference will be passed-by-value. So, there will be 2 references pointing to the same Employee instance. One reference is employee and another is in the arraylist.
Does every Collection behave this way?
Yes. Actually, this is NOT a property of collections. This is the way java was designed. All mutable reference types behave in this way.
The local variable employee and the first element of the list are two different references to the same object. That's why modifying the referenced object (via setName, for example) on one of them will be visible via the other.
However, if you replace the reference by assigning a different one, it will not effect the other.
E.g.:
employee = new Employee();
employee.setName("Vishrant");
Now employee and the first element of the list reference different objects, so the element in the array will not be called "Vishrant".