create a class to model a list - java

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}

Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.

Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.

you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Related

Generic linked list inside of linked list?

I am trying to write a program which stores information about a person in a linked list. I made a simple person class to store the name, age and addresses in the list. I would also like to store multiple addresses for EACH person, and a fact about the place in another linked list, inside the person class.
So for example, "Tara" can have a home address of "10 Central Ave" and a work address of "5 Willow street" etc. The problem is, I don't know how to have a linked list inside another.
My goal is to check whether the person's name is already on the list, and if so, add another address for them. (So that there is no repeats). I am a beginner and can really use some help.
public class Person {
private String name;
private int age;
public LinkedList <String> adresses;
public Person() {
name = "default";
age = 0;
adresses = new LinkedList<>();
}
public Person(String n, int a) {
name = n;
age = a;
}
public LinkedList<Adress> getAdresses() {
return adresses;
}
public void setAdresses(LinkedList<Adress> adresses) {
this.adresses = adresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return name+" "+age+" "+adresses;
}
}
public class Adress {
public String adress;
public String fact;
public Adress(String a, String f) {
adress = a;
fact = f;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getFact() {
return fact;
}
public void setFact(String fact) {
this.fact = fact;
}
}
public class Test {
public static void main(String[] args) {
Person Tara = new Person("Tara",35);
Person Judah = new Person("Judah",28);
Person Mark = new Person("Mark",45);
Person Seth = new Person("Seth",23);
LinkedList<Object> tester = new LinkedList<>();
tester.add(Tara);
tester.add(Judah);
tester.addLast(Mark);
tester.addLast(Seth);
System.out.println(tester);
}
}
How is about to use the next classic data structure for your project?
public class Person {
private String name
private int age;
public List<Address> addresses;
//...
}

Sending a List of different objects and returning the sum of their properties

I have to classes
public class Consumer{
private String name;
private int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
and next
public class Donor {
private String name;
private int amount;
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
now i have another class which contains a method method1()
public class GenericClass<T> {
public void method1(List<T> list){
Iterator i = list.iterator();
while (i.hasNext()){
}
}
}
and My main method is
public class MainMethod {
public static void main(String[] args) {
List<Donor> d = new ArrayList<>();
Donor donor = new Donor();
donor.setAmount(500);
donor.setName("bill");
Donor donor1 = new Donor();
donor.setAmount(1250);
donor.setName("linda");
d.add(donor);
d.add(donor1);
GenericClass genericClass = new GenericClass();
genericClass.method1(d);
}
}
i want to make this method1() dynamic and return a dynamic result.
so if i send the list of Consumer then it should return me the sum of all salaries and if i send the list of Donor then it should send me the sum of amount donated ?
how can this be achieved ?
First, you'd probably not make the class GenericClass generic but the method method1().
Then you could provide a ToIntFunction<T> which takes an object of type T and returns an int value. Thus your method could look like this (Java8 code):
public <T> int method1(List<T> list, ToIntFunction<T> transformation){
return list.stream().collect(Collectors.summingInt(transformation));
}
You'd then call that method like this:
int sumSalaries = method1(consumers, Consumer::getSalary);
int sumDonations = method1(donors, Donor::getAmount);
Pre-Java8 code would be possible as well but it would be a little bigger (you'd need to provide ToIntFunction, implementations of that interface and a slightly larger method body).
Alternatively you could use an Interface that's implemented by both classes but that would require you to use a common method name (e.g. getAmount() or getIntValue() etc.)

Accessing 2 models with 1 controller in Java MVC?

Is accessing 2 models with 1 controller in Java MVC alright?
The code looks similar to this:
This is the 1st model
public class People {
private String id, name;
public People(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
I'm still not sure about PeopleList class necessity. This is the 2nd model.
public class PeopleList extends ArrayList<People>{
#Override
public boolean add(People e) {
return super.add(e);
}
#Override
public int size() {
return super.size();
}
}
Here is the controller:
public class PeopleListController {
PeopleList peopleList;
public People findPeopleById(String id) {
People person = new People("", "");
for (People p : peopleList) {
if (p.getId().equals(id)) {
return p;
}
}
return person;
}
}
In the peopleListController, I accessed people using p.getId().
Is it alright? If it is, then it means I don't need to create
peopleController.
Or should I access p.getId() via a new controller
called peopleController?
Or should I just remove the peopleList class
and make an arrayList in this controller? ArrayList peopleList
Thank you for your time.

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

How to create a roster of students in java

I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}

Categories