About ArrayList in future use? - java

I am a java beginner and learning the oop concept. I already success to store the object value into a arraylist and i try to display the arraylist in the main method. But the problem is if i remove the add value code in the main method and display again the arraylist. The arraylist will show the null value which is []. Please help me and is this is my understanding problem or need to store in txtfile? database or what to get the or store the arraylist and can use for display all the record, update or delete that i add before
This is for my practice project and unuse the database to create a POS system based on oop concept. I had learn php and c# before and i do the same type project and not very confused because of using database. But now i feel confused how to use the java to create it and can has ability to create member, update member profile and etc based on oop concept. Please help me or give the suggestion. Very thank you.
my super class
class Person {
private List<Customer> customers;
private String name;
private String gender;
private String email;
public Person(){
}
public Person(List<Customer> customers){
this.customers = customers;
}
public Person(String name, String gender, String email){
***
}
public List<Customer> getCustomers(){
return customers;
}
public void addCustomer(Customer customer){
customers.add(customer);
}
//Getter
***
//Setter}
my subclass
class Customer extends Person{
private int custID;
private static int customerID = 10001;
public Customer(String name, String gender, String email,int custID){
super(name, gender, email);
this.custID = custID;
customerID++;
}
public int getCustID(){
return custID;
}
public static int getCustomerID(){
return Customer.customerID;
}
public String toString(){
return String.format("%d%30s%7s%30s\n", getCustID(), getName(), getGender(),getEmail());
}
}
My main method
public class POS {
public static void main(String[] args) {
Customer p1 = new
Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new
Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
List<Customer> cList = new ArrayList<>();
cList.add(p1); //if remove
cList.add(p2); // if remove
Person customer = new Person(cList);
System.out.print(customer.getCustomers());
}
}
i expect if write the code in main like
{ Person person = new Person();
System.out.print(person);
}
will display the result that i add before

If you don't want to add the customers to an ArrayList in your main-function a good way to do it would be to set the List<Customer> static in your Person-class and adding the customers as they get created.
public class Person {
private static List<Person> customers = new ArrayList<>();
public static List<Person> getCustomers() {
return customers;
}
private String name;
private String gender;
private String email;
public Person(String name, String gender, String email) {
this.name = name;
this.gender = gender;
this.email = email;
customers.add(this);
}
/* getters */
}
now in your main()-function you only have to create the Customers and they automatically get added to the customers list and therefore you can then get them by calling the static function getCustomers()
public static void main(String[] args) {
Customer p1 = new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
System.out.print(Customer.getCustomers());
}
To store them you would have to implement some kind of storage system like MySQL or simply a text file if you don't really have to access them from everywhere. You will find plenty of tutorials here on Stackoverflow in how to do that.
EDIT
#andy-turner pointed out that doing customers.add(this); inside a constructor really is a pain. So you could just create the ArrayList<Customer> in your Main-class and then work like this:
private static ArrayList<Customer> customers = new ArrayList<>();
public static void main(String[] args) {
customers.add(new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID()));
customers.add(new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID()));
System.out.print(customers);
}

Variables in memory are ephemeral
An ArrayList, like all of the Java Collections Framework, is a structure for holding data in memory. When your program ends its execution, all of that memory is freed. Your ArrayList is destroyed.
Storage
If you want to share data between runs, you must store it.
You can open a file in storage and write data values as text. On next run, read that file, parse the text back into objects, and populate a new ArrayList.
You can open a file and have your ArrayList write itself to storage using Java Serialization technology. Or you can do the serialization yourself with another serialization format.
Or send your data values to a database, which in turn writes them to storage. On next run, retrieve from database.
Or pass your data over the network to some service which accepts the data on your behalf. On next run, ask the service for your data.
All of this is too broad to discuss on Stack Overflow. You need to do your own research and learning.
Empty array versus NULL
The arraylist will show the null value which is [].
The string [] represents an empty array, an array holding no elements. Such array is not null! Null means no array at all.
Imagine a bookshelf holding books. That’s like an array holding elements. Remove the books. The empty shelf is like an empty array, with no elements. Now take down the bookshelf and burn it. That’s a null array, meaning no array at all.

Related

Is there a way to create a variable in JAVA that stores a arraylist and each element in the arraylist has its own list? name of elements given by user

Image of variable hierarchy (Please Check)
I want this specific variable to be a list of usernames, and each of these users will have some bookings... I tried adding an arraylist within an arraylist but that doesnt allow the user to name the usernames, they have to be predefined, please give me a method to do this.
You can store any kind of object in an ArrayList.
You could define your own class Booking that contains information about a booking:
public class Booking {
// ... whatever information is necessary for a booking
}
And then define a class User that contains information about a user, including a list of bookings:
public class User {
private String name;
private List<Booking> bookings = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Booking> getBookings() {
return bookings;
}
// ... other methods as necessary
}
And then you can make an ArrayList of User objects, where each User object contains a list of Booking objects:
List<User> users = new ArrayList<>();

ContactEntry( ) in ContactEntry cannot be applied

I am trying to make an association list for names and emails under a contact list for class. But I don't know what is wrong with my code or really, more accurately, what it is missing?
The directions are:
"One particularly common data structure is association lists. The standard example of an association list is a dictionary. A dictionary associates definitions with words. Given an word, you can use the dictionary to look up its definition. We ca think of the dictionary as being a list of pairs of the form (w,d), where w is a word and d is its definition. A general association list is a list of pairs (k,v), where k is some "key" value, and v is a value associated to that key. In general, we want to assume that no two pairs in the list have the same key. The basic operation on association lists is : Given a key, k, find the value v associated with k, if any.
Association list are very widely used in computer science. For example, a compiler has to keep track of the location in memory associated with each variable. It can do this with an association list in which each key is an variable name and the associated value is the address of that variable in memory. Another example would be a contact list, if we think of it as associating an email address to each name on the list. The items in the list could be objects belonging to the class:
The data for a contacts list consists of a ArrayList of ContactEntry and an integer variable to keep track of how many entries are actually stored in the list. A contact list could be an object belonging too the class:
Note that the search method, getEmail, returns the value that it finds associated with the key, name. This is often done with association lists.
The program could use a lot of improvement.
Modify ContactEntry adding setters, getters, a default constructor, and a constructor whose input is a name and email.
Modify ContactList to use the above and add its own setters, getters and a default constructor.
A contact list is pretty useless unless the data in the list can be saved permanently -- that is, in a file. Add the following methods to the contact list program, such that it keeps its list of names and email addresses in a file.
Thank you to anyone who helps me in advance. I am not the brightest star.
Some sample and starting code was provided but I am sure the issue is past that. I have tried googling the question but everything is different to the point that I am not sure exactly what my problem is.
public class ContactEntry {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
}
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class ContactList {
private ArrayList<ContactEntry> list=new ArrayList<ContactEntry>();
private int entries=0;
public void addEntry(String name,String email){
ContactEntry entry=new ContactEntry(name, email);
list.add(entry);
entries++;
}
public String getEmail(String name){
for(ContactEntry entry:list){
if(entry.getName().equals(name)){
return entry.getEmail();
}
}
return null;
}
public static ContactList LoadContacts(String filepath){
File file=new File(filepath);
try (Scanner scan=new Scanner( file )){
ContactList contactList=new ContactList()
while(scan.hasNext()){
String line=scan.nextLine();
int pos=line.indexOf(':');
String name=line.substring(0,pos);
String email=line.substring(pos+1);
contactList.addEntry(name,email);
}
return contactList;
}
catch (FileNotFoundException e){
e.printStackTrace();
return null;
}
}
public void storeContacts(String filepath){
File file=new File(filepath);
try(PrintWriter pwt=new PrintWriter(file)){
for(ContactEntry entry:list){
pwt.println(entry.getName()+":"+entry.getEmail());
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
ContactList contactList=new ContactList();
ContactList.addEntry( name:"tim",email:"tim#gmail.com");
ContactList.storeContacts(filepath:"contacts.txt");
}
}
You need what is called a constructor. Oracle says
A class contains constructors that are invoked to create objects from the class blueprint.
The constructor allows you to make an object which holds data. By default, all classes have a "default constructor" which is just empty and looks like
public ContactEntry() {
}
You need a constructor which takes in String name and String email. This would look something like
public ContactEntry(String name, String email) {
this.name = name;
this.email = email;
}
You haven't defined a constructor for your class, which means it has the implicit no-argument constructor only (new ContactEntry()). If you want a constructor that takes name and email, you must define it.
There should be a parameterized constructor in ContactEntry class.
public ContactEntry(String name,String email){
this.name=name;
this.email=email;
}

Is there a better way of accessing ArrayList object elements?

Took me a bit to figure this out but Im just wondering if there is a cleaner way to do this
this is the gist of my main
public class Main {
private static Bank Chase = new Bank();
//This is the function in main to add a transaction to a specified customer of a branch
public static void addTransaction() {
System.out.println("Enter the name of the branch");
String branch = scanner.nextLine();
System.out.println("Enter the name of the person");
String name = scanner.nextLine();
System.out.println("Enter the amount you would like to add");
double amount = scanner.nextDouble();
scanner.nextLine();
Chase.getBranchList().get(Chase.branchIndex(branch)).getCustomerList().get(Chase.getBranchList().get(Chase.branchIndex(branch)).customerIndex(name)).addTransaction(amount);
}
}
This last line is really long and confusing to others this is what it does
//gets the branchlist -> gets the specified branch -> gets the customerlist -> finds the specified customer -> adds transaction
these are the other relevant parts of the classes the function references
public class Bank {
private ArrayList<Branch> branchList = new ArrayList<Branch>();
public ArrayList<Branch> getBranchList() {
return branchList;
}
public int branchIndex(String name){
for(Branch branch: branchList){
if(branch.getName().equals(name)){
return branchList.indexOf(branch);
}
}
return -1;
}
}
public class Branch {
private String branchName;
private ArrayList<Customer> customerList;
public ArrayList<Customer> getCustomerList() {
return customerList;
}
public int customerIndex(String name){
for(Customer customer: customerList){
if(customer.getName().equals(name)){
return customerList.indexOf(customer);
}
}
return -1;
}
public class Customer {
private String customerName;
private ArrayList<Double> transactions = new ArrayList<Double>();
public Customer(String customerName, double amount) {
this.customerName = customerName;
this.transactions = new ArrayList<Double>();
transactions.add(amount);
}
public String getName() {
return customerName;
}
public void addTransaction(double transaction){
transactions.add(transaction);
}
}
So is there any more readable way of accessing these elements that are in object ArrayLists? I think the last line in addTransaction() looks a bit redundant.
Rather than one long line you could
a) split the code into multiple lines
Chase.getBranchList().get(Chase.branchIndex(branch))
.getCustomerList()
.get(Chase.getBranchList()
.get(Chase.branchIndex(branch))
.customerIndex(name))
.addTransaction(amount);
b) stored the returned values of each get into a local variable, especially the code that it re-calling the same methods e.g. Chase.branchIndex(branch) and Chase.getBranchList()
At the moment you are assuming unique customer/branch names, and then cycling through your array list to find the customer by name. This assumption is fine, if it's a valid assumption but could mean that there are more optimal solutions. I would recommend a refactor of your code to utilise a java hash map:
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Basically, this will mean that you can access the customer/bank directly by name and will simplify your code greatly! It will also have performance benefits.
For your scenario this refactor would look similar to this:
public class Branch
{
private HashMap<String, Customer> _customers;
private String _branchName;
public Branch(String branchName)
{
_branchName = branchName;
_customers = new HashMap<String, Customer>();
}
public Customer getCustomer(String customerName)
{
return _customers.get(customerName);
}
}
If you follow the same for Bank, you should be able to access a Customer and add a transaction as follows:
Chase.getBranch(branch).getCustomer(name).addTransaction(transaction);
Let me know if you need help converting Bank :)
You are on the right track, but you've got some minor design flaws.
Step 1: Add a method called getBranchByName(String branchName) to your Bank class that returns a Branch object and get rid of your branchIndex() method:
public Branch getBranchByName(String branchName) {
return branchList.stream()
.filter(branch -> branch.getBranchName().equals(branchName))
.findAny()
.get();
}
Step 2: Add a method called getCustomerByName(String name) to your Customer class that returns a Customer object and get rid of your customerIndex() method:
public Customer getCustomerByName(String name) {
return customerList.stream()
.filter(customer -> customer.getCustomerName().equals(name))
.findAny()
.get();
}
Step 3: Now, method call in your main() method becomes more compact, simple and easy to read:
Chase.getBranchByName(branchName).getCustomerByName(customerName).addTransaction(amount);
Note: I've used Java 8 streams as you can observe. If you are not allowed to use Java 8 streams, you can just stick with classic imperative style of programming by writing for() loops as you have done earlier. As a quick example, if you want to write getBranchByName(String branchName) in old fashioned Java 7 style, your loop looks like this:
for(Branch branch : branchList) {
if(branch.getBranchName().equals(branchName)){
return branch;
}
}

Infinite loop when trying to populate a list of no more than two Hospitals

In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.

Basic Object Oriented Programming

I am currently studying Java and have been asked to write a program that deals with
actors and films as classes.
The actor class has the following attributes:
Name, Address, age, myFilm (an array or arraylist to hold all the films a particular actor
has starred in.
The film class has these attributes:
Name, Code (String, String)
I have implemented these classes with getter and setter methods to handle the data:
My actor class so far:
public class actor {
private String name;
private String address;
private int age;
int[] myFilms = new int[3];
public actor (String name, String address, int age) {
}
public void setName (String name) {
this.name = name;
}
public void setAddress (String address) {
this.address = address;
}
public void setAge (int age) {
this.age = age;
}
public void setFilm () {
}
public String getName () {
return name;
}
public String getAddress () {
return address;
}
}
My film class:
public class film {
private String name;
private String code;
//Constructor
public film () {
}
public void setName (String name) {
this.name = name;
}
public String getName (){
return name;
}
public String getCode (String name) {
//Get code:
//Split Function
String[] words = name.split("\\s+");
String code = "";
for (int i=0; i < words.length; i++) {
code = code + words[i].charAt(0);
code = code.toUpperCase();
}
return code;
}
}
I'm hitting a brick wall with how to approach making the program dynamic to display each actors total films. This is for a college assingnment and I am also required to do a deep copy of the array at some point. I am almost completely new to OO so this is proving a tricky task for me.
Any words of advice or a point in the right direction would be hugely appreciated.
Two comments about your classes...
Why not declare the films of an actor like this:
private List<Film> myFilms = new ArrayList<Film>();
This way, you will be able to add and remove film object references dinamically from your actor objects. You can implement getter and setter for the list and manipulate it from outside, for example. Lists (or Collections in general) are much easier to manipulate than primitive arrays.
Consider declaring classes with first capital letter, it's a convention. For example: Actor, Film.
Consider extracting a "actor that play in film" to another class, to decouple film out of actor (actor can also do theathre spectacles, vioce dubbig etc, not specialy movies.)
class ActorRole {
private Actor actor;
private Movie movie;
private int dollarsSallary;
private int scenesPlayed;
// etc.
}
If you don't want to, I'm almost sure that better create dependency from Movie to Actor than from Actor to Movie, because Movies almost surely have actos:
class Movie {
private List<Actor> actors = new ArrayList<Actor>();
}
This makes harder to count actor statistics (you have to iterate over all Movies) but I think this is a better design.
To count single actor shows:
for ( Movie movie : listOfAllMovies ) {
if ( movie.getActors().contains( myActor ) ) { // read about equals() in Java !
timesPlayed++;
}
}
If you want to make a ranking for more actors, you can use Map<Actor,Integer> to map actors to they times played counters.
This can be a lengthy operation, so you can think about cashing the results (like in above map) - the solution can be map, ActorStatistics class, simple timesPlayed field in actor etc. etc.
Don't be afraid to objects
Don't do a hard workaround to mape films to id (like your id, which is propably connected to your film code String, wich add another type-incompatibility issue.
Try to use more object references instead of workarounds, and List instead of array.
Generally, read about Collections in Java, like ArrayList and HashMap and also overriding equals() and hashCode(), and in general OOP Single responsibility principle and Class cohesion
You can compose a auto-increment container inside class actor, like vector ArrayList and so on. Or you could implement a dynamic array by yourself.
If u have a database which has a table with username and film(ID) & etc, u can create a class as follow,
Class Film{
private String actorName;
private String filmCode;
private String filmName;
....getter & setter methods
...
}
then u can create a method to get data list of Film class.
Eg:
List<Film> filmList = new ArrayList<Film>();
String actorName = "Arnold";
filmList = dbCon.getFilmListByActor(actorName);
your getFilmListByActor method should be like this,
public List<Film> getFilmListByActor(String actorName){
List<Film> filmList = new ArrayList<Film>();
//Query for get film list by actor
//assigne filmList to result set
enter code here
return filmList;
}

Categories

Resources