I want to make a program to create people and to show a list of such persons, but do not know if I am doing well and neither logic using "arraylist" to print the results anyone can help me? Thank you very much.
package person;
import java.util.*;
public class Person {
public int Id;
public String Name;
public boolean Show;
public ArrayList people;
public Person(
int identificator,
String thename,
boolean showornot
){
this.Id = identificator;
this.Name = thename;
this.Show = showornot;
}
public void InsertPerson(Person person, ArrayList list){
this.people = list;
list.add(person);
}
}
The main:
package person;
import java.util.*;
public class Trying {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
Scanner stdin2 = new Scanner(System.in);
Scanner stdin3 = new Scanner(System.in);
Scanner stdin4 = new Scanner(System.in);
ArrayList list_of_people;
list_of_people = new ArrayList();
int option = 0;
int identificador = 0;
String name = "";
boolean show = true;
name = “Toni”;
Person person1 = new Person(identificador, name, true);
person1.InsertPerson (person1, list_of_people);
Iterator ite = list_of_people.iterator();
while(ite.hasNext()){
System.out.println(list_of_people);
}
}
Thanks!
Problem: You are creating the arraylist "people" as a property of each "person" (Saying, each person has a list of people)
Quickfix:
Move public ArrayList people; to your Trying class.
Move public void InsertPerson(Person person, ArrayList list) to your Trying class as well.
Better fix:
I recommend using a PeopleManager class - which contains the arraylist "people" and the InsertPerson method. Then, you use the PeopleManager in Trying to build your people list.
public class PersonManager
{
ArrayList<Person> people;
public PersonManager()
{
people = new ArrayList<Person>();
}
public void InsertPerson(Person person)
{
people.add(person);
}
}
Then, you can remove the arraylist from Person, and the method InsertPerson from Person. You'll need to create a PersonManager in your Trying class.
public ArrayList people; does not belong in the Person class. I would suggest using it your client code (the Trying class) or creating a class People that inherits from ArrayList. You can then add a InsertPerson function to that class if you wish.
I would also suggest using a ArrayList for your collection rather than an ArrayList. See a generic collections tutorial here. You should also create getter/setter moethods instead of using public fields.
So, your classes would be:
public class Person { // ...
public class People extends ArrayList<Person> {
public void InsertPerson(Person person) {
this.add(person);
}
// ...
What everyone else is saying is true, but I think theoretically your code should still work. There is a problem with this line however...
while(ite.hasNext()){
System.out.println(list_of_people);
}
You are outputting the whole list every iteration and probably infinite looping. Change it to something like this...
while(ite.hasNext()){
Person curPerson = (Person)ite.next();
System.out.println(curPerson.Name);
}
A slightly more elegant solution is to ditch the iterator for a foreach loop...
for (Person person : list_of_people) {
System.out.println(person.Name);
}
Related
So I'm making a plugin and I want to put two ArrayList (of two different teams) to one Hashmap, so I can get both of the teams in this method:
public static Teams getTeam(Player player) {
if (!hasTeam(player))
return null;
return zombiesTeam.get(player) && survivorsTeam.get(player);
}
Here is the two ArrayList and a Hashmap that I want to have:
public static HashMap<zombiesTeam, survivorsTeam> playerTeams = new HashMap<zombiesTeam, survivorsTeam>();
public static ArrayList<Player> zombiesTeam = new ArrayList<Player>();
public static ArrayList<Player> survivorsTeam = new ArrayList<Player>();
P.S. I know that this code isn't correct
Please ask me for any further additional information
Thanks in advance.
You should do something like this:
public static HashMap<String, ArrayList<Player>> playerTeams = new HashMap<>();
playerTeams.put("zombies", zombiesTeam);
playerTeams.put("survivors", survivorsTeam );
If you want to represent all your "teams" by a hashmap from the team name to the list of team members, I would suggest this:
// In the same class where zombiesTeam and survivorsTeam are declared
public static Map<String, List<Player>> getTeamsByName() {
Map<String, List<Player>> teamsByName = new HashMap<>();
teamsByName.put("zombiesTeam", zombiesTeam);
teamsByName.put("survivors", survivorsTeam);
return teamsByName;
}
However, be sure that you need to use static fields and methods. Your model doesn't suggest this.
For instance, you could rather declare a Team class and a Player class. Since you already have the Player class, here is how I would make the Team class:
public class Team {
private String name;
private Set<Player> teamMembers = new HashSet<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return this.teamName;
}
public Set<Player> getTeamMembers() {
return this.teamMembers;
}
public addPlayer(Player player) {
this.teamMembers.add(player);
}
public removePlayer(Player player) {
this.teamMembers.remove(player);
}
public reset() {
this.teamMembers.clear();
}
}
Be sure to override equals and hashcode for HashSet and HashMap to work correctly. More information about this here:https://www.geeksforgeeks.org/equals-hashcode-methods-java/
So I want to use a method to write multiple objects to respective files. However I do not know how to import the array of Objects without defining the specific Object.
The people is class is purely for storing the created objects in arrays so it is easier to access across other classes.
For example
public class People {
private Student[10];
private Teacher[10];
public void setStudentArray(Student, index) {
Student[index] = Student;
}
public void setTeacherArray(Teacher, index) {
Teacher[index] = Teacher;
}
}
public class Student extends People {
String name;
int StudentID;
public String getName() {
return name;
}
}
public class Teacher extends People {
String name ;
int Teacher ID;
public String getName() {
return name;
}
}
public class Main {
People p = new People();
public void main (String[] args) {
Student s = new Student("default-name" , 1);
p.setStudentArray(s, 0);
Teacher t = new Teacher("default-name", 1);
p.setTeacherArray(t, 0);
outputName(p.getStudentArray, 0);
outputName(p.getTeacherArray, 0)
}
//THIS IS WHERE I AM STRUGGLING I dont know how to pass teachers or students array to it.
//I want the Object[] parameter to accept both Student[] and Teacher[]
public void outputName(Object[], index) {
System.out.println(Object[index].getName);
}
}
I think that my Method taking an Object[] is wrong but I do not know how to approach it otherwise. I believe the issue is that Object[] is an entirely different class to Teacher[] and Student[] and this is where I am going wrong.
I want to use the .getName method in both the classes of Teacher and Student in order to print the name of the Teacher of Student. (Merely so I can see the passing is working.)
If this is just not possible I guess I will just not try a method that can take different objects.
I know that I can just use two methods one for students and one for teachers but I want the method to work for multiple objects so that I can add more object arrays to it.
So People class is extended by both Student and Teacher.
What commonalities are here?
String name is present in both Student and Teacher
public String getName() is also present in both Student and Teacher
You can move these commonalities to People class. Also ensure to remove the name attribute and getName from Student and Teacher class
So your People updated class can be:
public class People {
private String name; //Newly added
private Student[10]; //This ideally shouldn't be in People class rather a different class
private Teacher[10]; //This ideally shouldn't be in People class rather a different class
public void setStudentArray(Student, index) {
Student[index] = Student;
}
public void setTeacherArray(Teacher, index) {
Teacher[index] = Teacher;
}
public String getName() {
return name;
}
public void setName() {
this.name = name;
}
}
The outputname method should be like:
public void outputName(People[] people, index) {
System.out.println(people[index].getName());
}
NOTE: I am not correcting the syntax here, but just giving an idea.
What #Li357 said is right... You have to change your modeling a bit. Even if you managed to pass Student[] as an Object[], you wouldn’t be able to call the getName method as it’s not an Object method.
So a better modeling would be to make the getName method a People method, and both Student and Teacher classes would inherit it.
Then you could receive People[] as the outputName method argument, and use the getName method inside.
First of all learn how to declare array and choose valid variables.
In your People class do following modifications.
public class People {
//Declare arrays like this.
private Student[] student;
private Teacher[] teacher;
//Initialize arrays
public People(){
student = new Student[10];
teacher = new Teacher[10];
}
public void setStudentArray(Student s,int index) {
student[index] = s;
}
public void setTeacherArray(Teacher t, int index) {
teacher[index] = t;
}
//Add getter methods
public Student[] getStudentArray(){
return student;
}
public Teacher[] getTeacherArray(){
return teacher;
}
}
Inside sub classes Student and Teacher add Argument constructor
Finally in your outputName method you can do something like this.
public static void outputName(Object[] obj, int index) {
if(obj instanceof Student[]){
Student[] s = (Student[])obj;//parsing to student array
System.out.println("Student name : "+s[index].getName());
}
if(obj instanceof Teacher[]){
Teacher[] teacher = (Teacher[])obj;//parsing to teacher array
System.out.println("Teacher name : "+teacher[index].getName());
}
}
Output:
Student name : default-name
Teacher name : default-name
we have
class Student
{
String name,
int age,
String specialization
}
and
class Students
{
List<String> names,
List<Integer> age,
List<String> specialization
}
Students object is basically a structure that holds field values of Student class,
What is the best way to fill Students object without using reflection.
Edit: we have a specific requirement of having Students class as it is, the reason for this is we don't always want all the information in Student class and if we have List it would allocate memory for the fields that we are not interested in.
Don't create class Students. Hold a list of Student
List<Student> students = new ArrayList<Student>();
And to access a student data you can use
students.get(0).name;
As a side note, you should learn about getters and setters.
I wouldn't recommend creating a class named "Students" for this purpose. Your intention is to create a collection to hold the Student objects.
In this case, do the following:
List<Student> students = new ArrayList();
Also, pay attention to the capitalization: class is a keyword and should be spelled all lower-case.
EDIT After seeing a comment from venkat:
If you really need to create a class called Students then following should work (also similar answer provided above by another SO user):
class Students {
List<Student> students = new ArrayList();
}
This should work, but I would highly recommend not to use these type of class with the plural names!
PS: I am a CS prof teaching programming languages in a university and a long time developer/consultant.
Class Students {
List<Student> students;
}
Maybe you want to use a Decorator-Pattern (I don't think that i saves memory):
Implement a base class with the default field:
public class BaseClass implements INameGettable {
protected String name;
public BaseClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Add the default interface:
public interface INameGettable {
String getName();
}
Add a decorator to for an additional field e.g. age:
public class Decorator implements INameGettable {
protected INameGettable nameable;
protected int age;
public Decorator(INameGettable nameable, int age) {
this.nameable = nameable;
this.age = age;
}
public String getName() {
return nameable.getName();
}
public int getAge() {
return this.age;
}
}
Usage:
// First object contains only name
INameable namegettable = new BaseClass("Test1");
namegettable.getName();
// Second object contains name and age
Decorator agegettable = new Decorator(new BaseClass("Test2"), 77);
agegettable.getName();
agegettable.getAge();
Going for the obvious answer here.
class Students
{
List<String> names;
List<Integer> age;
List<String> specialization;
public Student(List<Student> students) {
addStudents(students);
}
private void addStudents(List<Student> students) {
names = students.stream
.map(Student::getName)
.collect(Collectors.toList())
age = students.stream
.map(Student::getAge)
.collect(Collectors.toList())
specialization = students.stream
.map(Student::getSpecialization)
.collect(Collectors.toList())
}
}
I am just trying to add some objects to an ArrayList in eclipse, but i keept getting an error (Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList) under the 'persons.add(one);'. Any idea what I am doing wrong?
package thequestion;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class PersonComparator implements Comparator<Person>{
#Override
public int compare(Person o1, Person o2) {
return 0;
}
Person one = new Person("Kevin", "Gresmer");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
public void sortByLastName(List people) {
Comparator comp = new PersonComparator();
Collections.sort(people, comp);
}
}
public class Person {
private String firstName = null;
private String lastName = null;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The line persons.add(one) is a statement, and you can't have a statement outside a block of code (method, constructor, etc.). Also, your Comparator should contain code related to the comparison you are doing. I don't think it's the right place to store a list or implement the sortByLastName() method.
You can only initialize the instance variables in class and outside the methods.
You initialized persons. Then to apply methods, you need to put that line into some methods. So, may be you can update your Sort Method or create new one and make reference to that method from your sort method.
The first option as explained in the above comment.
class PersonComparator implements Comparator{
#Override
public int compare(Person o1, Person o2) {
return 0;
}
Person one = new Person("Kevin", "Gresmer");
List<Person> persons = new ArrayList<Person>();
private void addPersons(){
persons.add(one);
}
//persons.add(one);
public void sortByLastName(List people) {
addPersons();
Comparator comp = new PersonComparator();
Collections.sort(people, comp);
}
}
The point is we cannot write anything except the Instance variables. We have to cover them with methods. I hope this will solve your issue.
put below under sortByLastName method. Currently below code snippet not lying under any method.
persons.add(one);
Correct code should be
public void sortByLastName(List people) {
persons.add(one);
Comparator comp = new PersonComparator();
Collections.sort(persons , comp);
}
please note :- But my answer is in terms of compilation error. Ideally comparator should have code only related to comparison. Nothing else.
Obviously, you cannot do persons.add(...) in the middle of the class declaration.
You should certainly add one and persons in a main in the class Person, and keep your Comparator class clean with only the logic of comparison. The main will allow you to test your code.
The same idea for the sortByLastName(...) you can declare it as static in Person class.
Then you can test with the main, e.g.
// In class `Person`
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
Person one = new Person("Kevin", "Gresmer");
persons.add(one);
Person two = new Person("Elvis", "Presley");
persons.add(two);
System.out.println(sortByLastName(persons));
}
Note for the above to provide a sensible output, you need to add a toString() method to the Person class.
This is possibly a simple problem but I am having issues. I have 3 classes. A Student class that contains a setmethod:
public boolean setName(String fname)
{
this.name = fname;
return true;
}
A TestClass with a main that passes a string to the setmethod
static Student action;
public static void main(String[] args)
{
action.setName("John");
}
and a Classroom class that contains an add student method.
public boolean add(Student newStudent)
{
???
return true;
}
I know how to create and add an object to an array list but I am confused as to how to do it using 3 separate classes. My array list init is:
List<Student> studentList = new ArrayList<Student>();
How would I associate the attributes(name in this case) being set in the Student class to a new object being created in the Classroom class?
I think you should follow the principle of least surprise i.e., make sure the methods you create do exactly what you need them to. In your example, your setName and add methods return a boolean for some reason. Typically, setter methods don't return booleans, unless you're doing some sort of a DB insert like operation and want to make sure that your object was actually inserted.
Also, a typical idiom would be to create the controller object (i.e., TestClass) in the static main method and then initialize whatever is necessary in its constructor or by calling methods on the created TestClass object inside the main method itself.
Here's a solution.
public class TestClass {
private Classroom c;
public TestClass() {
c = new Classroom();
private Student s = new Student();
s.setName("John");
c.add(s);
}
public static void main(String[] args)
{
new TestClass();
}
}
public Classroom {
private List<Student> studentList;
public Classroom() {
studentList = new ArrayList<Student>();
}
public boolean add(Student newStudent) {
studentList.add(newStudent);
return true; //not sure why you're returning booleans
}
}
Your student class looks good, your classroom class should contain a list of students, and ways to add/remove/list students. Your test class should create new students which you can then add to your classroom.
I assume you want a Test Class which is a test event like midterm or final, and you want to put Student and ClassRoom in the Test Class.
So you get three classes, and they're all related. If this is the case you want, then you can do this. (This is a very simplified version!!)
class Test{
String name;
HashMap<ClassRoom, ArrayList<Student> > roomMap;
// ... other functions
}
// you can use ClassRoom as key and Student list as value.
// A ClassRoom key will return a value which is a Student list containg students who are going to take a test in that room.
public static void main(String[] args) {
Test test = new Test();
test.name = "MidTerm";
test.roomMap = new HashMap<ClassRoom, ArrayList<Student> >();
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("John"));
students.add(new Student("Mark"));
ClassRoom room = new Room("R123");
test.roomMap.put(room, student);
// If there are a lot of test, then you could manage test in an ArrayList in your main.
ArrayList<Test> testList = new ArrayList<Test> ();
testList.add(test);
}
Maybe you could give more details of your requirement.