Java: Unable to print elements in ArrayList - java

OK, I have a bit of a conundrum. I'll say straight out that I'm working on a homework assignment and I've come to a stumbling point. I'm sure that I'm missing something obvious, but after hours of searching the internet and text books to try and find an answer to this, I'm butting up against a wall and I'm hoping someone can point me in the right direction.
I have created a class called "employee" that defines an employee object, it has getter and setter methods for the employee's name and sales totals. It looks as follows:
public class employee {
private String employeeName;
private double yearSales;
public employee(String employeeName, double yearSales)
{
this.employeeName = employeeName;
this.yearSales = yearSales;
}
public void setName(String employeeName)
{
this.employeeName=employeeName;
}
public void setSales(double yearSales)
{
this.yearSales=yearSales;
}
public String getEmployee()
{
return employeeName;
}
public double getYearsSales()
{
return yearSales;
}
}
I then have a method that is intended to instantiate an ArrayList that contains employee objects. I'm able to get as far as creating the ArrayList and adding information to it as shown below:
public ArrayList employeeArray(String name, double sales)
{
//Instantiate a new ArrayList object
ArrayList employeeList = new ArrayList();
//Initialize the values in the ArrayList
employeeList.add(new employee(name, sales));
return employeeList;
}
Where I am running into trouble is with attempting to print out the name value from the ArrayList, shown below:
System.out.println(employeeList.get(0).getEmployee());
I'm only adding one element so the index value should be correct, and I worked with ArrayLists in another Java course not too long ago and was able to do something similar to this in my code for those assignments. If I need to clarify anything more about this I'll be happy to. Of course, any assistance on this is greatly appreciated.

You should be using Generics if you have Java SE >= 5, so instead of ArrayList, use ArrayList<employee>. Otherwise, you'd need to cast its type from Object to Employee:
System.out.println(((employee)employeeList.get(0)).getEmployee());
Also, class and interface names in Java should start with an uppercase letter.

public ArrayList<employee> employeeArray(String name, double sales)
{
//Instantiate a new ArrayList object
ArrayList<employee> employeeList = new ArrayList<employee>();
//Initialize the values in the ArrayList
employeeList.add(new employee(name, sales));
return employeeList;
}

Youre trying to instantiate a new ArrayList with each call to employeeArray() method. Try maintaining a common ArrayList and add elements to it using this method.
Also +1 with using generics
And if you're new to Java, then do read this link as well: "Java Programming Style Guide (Naming Conventions)"
Assuming you've a class called EmployeeList where you have defined this method employeeArray(), you can update it to maintain new names in the list as follows (note that this is one sample solution, you are obviously welcome to tailor it to your need):
public class EmployeeList{
private ArrayList<Employee> employeeList;
public EmployeeList(){
//Initializing the employee arraylist
employeeList = new ArrayList<Employee>();
}
public ArrayList<Employee> employeeArray(String name, double sales){
//Initialize the values in the ArrayList
employeeList.add(new Employee(name, sales));
return employeeList;
}
}
Also note the use of generics and the naming conventions in the above code. This might be helpful for you.

Related

How to create a Hashtable using a method as a struct

My overall goal is to fill a Hashtable with employee data and be able to access/modify that data then print it out.
Given my Employee class here, can I use it like a struct in C? I'm trying to figure out how to initialize a Hashtable and fill it with this data but I'm sort of confused on how to implement it.
public class Employee {
private String empName;
private int empNum;
private String empJob;
public Employee(String empName, int empNum, String empJob)
{
this.empName = empName;
this.empNum = empNum;
this.empJob = empJob;
}
public int getEmpName()
{
return empName;
}
public String getEmpNum()
{
return empNum;
}
public String getEmpJob()
{
return empJob;
}
}
So, I tried this in main, using String as the key, so I want to use the names as the key so you can search by name. I'm also trying to manually fill it so I can test everything. Also, am I able to access say, the employee number on it's own? if so, how can I do this?
public class Main {
public static void main(String[] args)
{
Hashtable<String,Employee> EmployeeTable = new Hashtable<String,Employee>();
Employee Object = new Employee("Donald","Donald", 3, "Engineer");
}
}
Thanks in advance everyone!
You can add elements to your Hashtable using the put method. You just need to specify the key and the value.
Then you can retrieve values using the get method and specifying the key.
Example Usage:
Hashtable<String, Employee> table = new Hashtable<String, Employee>();
Employee bob = new Employee(...);
table.put("Bob", bob);
Then later you can say...
table.get("Bob");
and this will return Bob's Employee object for you.
Problems with your code:
There are a few problems with your code that you should be aware of.
1. Your Employee Constructor is wrong.
You've got a constructor for Product inside of your Employee class. This is illegal syntax and will not compile (I hope). Instead, you should use the Employee constructor.
2. Your Hashtable variable name matches the Object class.
You've named a variable Object. Object is the class that all java classes inherit from, so you really shouldn't name something this (if it even lets you at all).
The Object documentation mentions this...
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
3. Incorrect Hashtable types.
You've put the wrong types in your Hashtable declaration.
You wrote...
Hashtable<String, Employee> EmployeeTable = new Hashtable<String, Product>();
When really it should be...
Hashtable<String, Employee> employeeTable = new Hashtable<String, Employee>();
(Product changed to Employee)
(I also changed the variable to be lowercase)
Notes:
All of the documentation for Hashtable can be found here.
You may also be interested in using a HashMap instead of a Hashtable. They're almost identical but HashMap isn't threadsafe. You can see some of the differences here. If you really need a threadsafe map then I'd recommend ConcurrentHashMap, it's up to you to decide which one suits you the best though.
It's Java convention for variable names to start with lowercase letters. You don't have to follow this but it's definitely a good idea to. Syntax highlighters will no longer argue with you if you do.
What you want to achieve is rather this:
// Create my Hashtable using the diamond notation indicating to use the type arguments
// corresponding to the context which is <String, Employee> here
Map<String, Employee> EmployeeTable = new Hashtable<>();
Employee employee = new Employee("Donald", 3, "Engineer");
// put my employee into my map using empoyee's name as key
EmployeeTable.put(employee.getEmpName(), employee);
What you are looking for is Map#put(key, value)
After fixing several typo issues, your class Employee should be:
public class Employee {
...
public Employee(String empName, int empNum, String empJob)
{
...
}
public String getEmpName()
{
return empName;
}
public int getEmpNum()
{
return empNum;
}
...
}
NB: Hashtable is an outdated class, you should not use it anymore, if you don't intend to share it use an HashMap instead and if you want to share it use a ConcurrentHashMap
There are various things wrong with your class.
Example: the class is called Employee. Then the constructor must use that name, and nothing else!
So, it shouldn't read
public Product(String empName, int empNum, String empJob)
but
public Employee(String empName, int empNum, String empJob)
And then your call
Hashtable<String,Employee> EmployeeTable = new Hashtable<String,Product>();
could be correctly written down as
Hashtable<String,Employee> table = new Hashtable<>();
And no, a Hashtable is not a struct. A hashtable is a collection class; in other words: it is a Map. It maps a key (String in your case) to Employee objects.
But, well, stackoverflow is not a service where other people debug and explain your code to you. So, take my input as starting point; and for example: start reading the compiler messages.

Create ArrayList from array using temporary object

I know there are standard way by add a constructors to the class. But for classes with object superclass (has no-argument constructor) I tend to find using a temporary object simpler. Is there any down side for such an act.
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
// data available in two separated arrays
String[] dName = {"Sam","Ben","Joye","Sarah","Tim","Lucy","Jack"} ;
int[] dAge= {10,52,53,15,12,60,21};
// Array list to put the data in
ArrayList<Person> personList =new ArrayList<Person>(7);
for (int i=0;i<dName.length;i++){
Person tempPerson = new Person();
tempPerson.name= dName[i];
tempPerson.age= dAge[i];
personList.add(new Person());
personList.set(i,tempPerson);
tempPerson=null; //removes the reference
}
for (int j=0 ; j<personList.size();j++){
System.out.println(personList.get(j).name+" age is "+personList.get(j).age );
}
}
}
class Person{
String name;
int age;
}
the output
Sam age is 10
Ben age is 52
Joye age is 53
Sarah age is 15
Tim age is 12
Lucy age is 60
Jack age is 21
You should avoid statements that do nothing - an optimization would be to do
for (int i=0;i<dName.length;i++){
Person tempPerson = new Person();
tempPerson.name= dName[i];
tempPerson.age= dAge[i];
personList.add(tempPerson);
}
No need to first add the person to later replace it
No need to null the reference - the list will keep the reference to the temp object in any case.
Instead of setting values directly you could use setters (setName() instead of .name = )
If you'd use setters, you could implement a Builder pattern:
like this:
public Person setName(String aName) {
name = aName;
return this;
}
Resulting in something like
personList.add(new Person().setName(dName[i]).setAge(dAge[i]));
Then again - the two value constructor will probably be the easiest of all - and it don't matter that the super class doesn't have a constructor:
public Person(String aName, int aAge) {
name = aName;
age = aAge;
}
//You can have more than one constructor
public Person() {
}
and then
personList.add(new Person(dName[i], sAge[i]));
You should use a constructor for Person. Then you have just one call in your for-loop:
personList.add(new Person(dName[i], dAge[i])
Also, in your implementation, you are doing the necessary work twice, because you call personList.add(new Person()) and then you call personList.set(i, temPerson). If you don't want a constructor in your Person-class, a call of personList.add(tempPerson) for example would be enough.
Not really,
you could maybe make use of java8 streams, but why make your life harder, it wouldnt add anything new

Delete/Add a specific Element(int) in an Array

This subclass should be able to let the user choose a specific employee ID, type it into the command line and choose to either add it to the array list, delete it from the array list or simply request to see more information about the specific employee ID. I've tried so many things with no luck at all.
package WorkIDServerStorage;
public class EmployeeList{
private Employee[] theEmployee;
private int arrayEmployee;
public EmployeeList(){
theEmployee = new Employee[100];
arrayEmployee = 0;
}
public EmployeeList(int arraySize){
theEmployee = new Employee[arraySize];
arrayEmployee = 0;
}
public void setTheEmployee(Employee[] inputTheEmployee){
theEmployee = inputTheEmployee;
}
public void setArrayEmployee(int inputArrayEmployee){
arrayEmployee = inputArrayEmployee;
}
public Employee[] getTheEmployee(){
return theEmployee;
}
public int getArrayEmployee(){
return arrayEmployee;
}
public Employee addEmployeeID(Employee employeeAdd){
return theEmployee[arrayEmployee++] = employeeAdd;
}
public Employee deleteEmployeeID(int employeeDelete){
//Delete an employee record with a
//specified record number from the array
}
public Employee readEmployeeInfo(int employeeRead){
//Read the employee data for a specified record number
//From the array and display this data to the screen
}
#Override
public String toString(){
StringBuilder sb = new StringBuilder();
for(int x = 0; x < arrayEmployee; x++){
sb.append(theEmployee[x].toString()).append("\n");
}return sb.toString();
}
}
Arrays are fixed length data structures. They are much like a multi-storied building. You can't take a floor out from the middle of the building and expect it to stand.
ArrayList (as others have pointed out), are dynamic structures, much like a train. You can take out compartments as you wish, you can reconfigure it.
I would in fact recommend NOT using a List at all, but a Map that maps an ID to an employee record. Let us say you have the following employees in a list -
Alice
Bob
John
Ruth
If you delete "Bob" the ID's for John and Ruth are going to change. Not a good practice. If you use a Map instead, everyone can keep their assigned ID's and you just add to the map by incrementing the keys (or IDs).
Hope this helps.
For being able to dynamically adding or removing from an array, you should use List, or ArrayList. Typical arrays don't provide delete or add at runtime, since they are fixed-size and if you want to control the procedure by handling the indices or other tricks, you'll probably end up in a messy and hard to maintain code.
On the other hand, Lists in java are dynamically sized and provide add(), remove(), get() and other convenient methods, which in my opinion best suits you.
You should use an ArrayList in order to dynamically add and remove entries in your array.
Make your theEmployee array into an ArrayList by doing:
ArrayList<Employee> theEmployee = new ArrayList<Employee>();
You can add and remove by doing:
public boolean addEmployeeID(Employee employeeAdd){
return theEmployee.add(employeeAdd);
}
public Employee deleteEmployeeID(int employeeDelete){
return theEmployee.remove(employeeDelete)
}
I changed the return type of addEmployeeID to boolean because an ArrayList returns a boolean when you add an object.
For remove, int employeeDelete would be the index of the object in the array. When you remove an object, all the remaining objects get shifted to the left. So if you have an array [1,2,3] and you remove 2, it would become [1,3]. The indexes are moved.
You could also remove an object so this should work:
public boolean deleteEmployeeID(Employee employeeDelete){
return theEmployee.remove(employeeDelete)
}
Where employeeDelete is an Employee and the function returns a boolean.

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

What is the datatype of a Java varargs (...) parameter?

I am trying to add information from main()
to a items class where i am storing the information in a hashset
i have 3 classes
project - main()
libaray - addBandMembers function
Item - addband(String... member)
i am adding CD information. first, i add band, # of songs, title - which works good
then in another function i am trying to add the band members. I want to keep these separate.
Where i am having problems is assign the band members..
I understand that how Varargs works just not sure how to assign that to a string..
I will only show bits of code to keep this post simple and short..
this is what i have:
Main()
item = library.addMusicCD("Don't Let Go", "Jerry Garcia Band", 15, "acid rock", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Keith Godcheaux");
library.printItem(out, item);
}
Then, here the first function thats called..
public void addBandMembers(Item musicCD, String... members)
{
//musicCD.addband(members); // both cant find addband function..
//Item.addband(members);
}
Then in another class i am trying to add the information..
private String members;
public void addband(String... member)
{
this.members = member; // error
}
if i make the private String members; an array
then this function below errors.. incompatible type..
public String getMembers()
{
return members;
}
How can i do this?
oh ya, here is my set..
public class Library
{
private Set<CD> theCDs = new HashSet<CD>();
private Set<DVD> theDVDs = new HashSet<DVD>();
private Set<Book> theBooks = new HashSet<Book>();
if you need to see more code let me know..
Thank you so much..
A varargs argument resolves to an array.
So, change
private String members;
to
private String[] members;
Change your getter to return a String array instead of a String.
String... member gives you an array, so what you are looking at is a member that is of type String[].
I think once you get that, you kind of get over the hump of the issue.

Categories

Resources