I am doing homework and it states that I have to be able to remove a entry from an arraylist of objects.
I try to check if it contains the user id I want to remove but objects cannot contain strings
public class EmployeeProgramView extends FrameView {
ArrayList <information> database = new ArrayList <information>();
private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
information a;
String ID, firstName, lastName, startDate, annualSalary, linedUp;
ID = idInput.getText();
firstName = firstNameInput.getText();
lastName = lastNameInput.getText();
startDate = startInput.getText();
annualSalary = salaryInput.getText();
linedUp = (firstName+" "+lastName+" "+annualSalary+" "+startDate);
a = new information (ID, firstName, lastName, startDate,annualSalary);
database.add(a);
System.out.println(linedUp);
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp="";
for (int x=0; x<=database.size()-1; x++) {
temp = temp + database.get(x).ID + " "
+ database.get(x).first + " "
+ database.get(x).last + " "
+ database.get(x).start + " "
+ database.get(x).salary + "\n";
}
finalOutput.setText(temp);
}
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
String removeID;
removeID = idInput.getText();
if (database.contains(removeID)){
database.remove(removeID);
} else {
finalOutput.setText("No such ID in database");
}
}
class information{
String ID, first, last, start, salary;
information(String _ID ,String _first, String _last, String _start, String _salary){
ID = _ID;
first = _first;
last = _last;
start = _start;
salary = _salary;
}
}
}
So my question is? How do I remove a object?
The remove method will remove an object from array as long as .equals returns true when comparing that object and the object we are asking to remove. This is true for identical strings; other objects by defaults are only equal to themselves (still, you can add an object to array and retain another variable referring to it).
You can also always remove just by array index.
You may just need to use the method: List < T > #remove, to remove the object in question
Got it!
Thanks everyone for their input. really got my brain thinking different ways haha.
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp, removeID;
removeID = idInput.getText();
for (int x = 0; x<=database.size()-1; x++){
temp = database.get(x).ID;
if(removeID.equals(temp)){
database.remove(x);
}
}
}
You have to iterate through the Array and find the ID you are looking for. Just add this into your main class:
public void removeInformation(ArrayList<Information> database, String removeID) {
for(int i = 0; i < database.size(); i++) {
if(database.get(i).getID().equals(removeID)) {
database.remove(database.get(i));
}
}
}
This is unrelated to your question, but by convention classes are named with a capital letter, so your "information" class should be titled "Information".
Also, I just wanted to say that, in case you didn't know, before you type your class you can type import statements. For example:
import java.awt.event.ActionListener;
This way you don't have to type "java.awt.event.ActionListener actionListener" every time you want to use that class.
see basically,
you need to remove an object information from arraylist if the list contains information whose id is same as removeid.
so before removing , you need to do a check for the information id in the list
so go for iterating list and find information in each iteration and check its id equlas to removeid
if equals then do list.remove(information)
for (Information information: database) {
// check for ID is same as remove id
// if equals remove that entire object from list
if (information.ID.equals(removeID)) {
// remove object with ID same as removeid
database.remove(information);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My problem is I need to make a program where you can search for an employee based on their ID number. Which needs to be something like "E1" or "E2". I am struggling to find a way to search for numbers and letters in the same object. It only works when I use just a number like 1 or 2 by using Int.
How can I store both a letter and integer in an object? Is there something similar to String that stores letters or Int that stores numbers but for both letters and numbers?
Ex. I can search for my employe already but their ID is currently just "1" or "2" or "3". I need to change it to "E1" or "E2" etc. But it wont work with String or Int.
I am searching an array. In an employee class
You can check, if two Strings are equal, by using the equals method: String1.equals(String2);
Also, you could implement a new class implementing the interface Comparable. In this class you could split the ID into a String and an Integer part:
public class EmployeeID implements Comparable {
String s = null;
Integer i = null;
public EmployeeID(String s, Integer i) {
this.s = s;
this.i = i;
}
#Override
public void equals(EmployeeID id) {
return new String(s + i).equals(new String(id.s + id.i));
}
#Override
public void compareTo(EmployeeID id) {
return new String(s + i).compareTo(new String(id.s + id.i));
}
}
Of course, if you do not need to compare elements (which can be useful for sorting), you can just implement this wrapper class without the comparable interface.
The equals method compares two ids and is not implemented in the Comparable interface, but the Object class, which is the superclass of every class.
No code provided so I'm guessing as to what you actually are trying to do.
public class SomeIds {
private String[] ids;
public boolean isPresent(String id) {
for (String element : ids) {
if (element.equals(id)) {
return true;
}
}
return false;
}
/**
* returns the index of the first element matching the id
* provided or -1 if it is not found
*/
public int indexOf(String id) {
for (int index = 0 ; index < ids.length ; ++index) {
if (ids[index].equals(id)) {
return index;
}
}
return -1;
}
}
Unfortunately, you won't be able to mix types (i.e. numbers and letters). You'll have to use a String for storage of the ID, in which case, you can use equals to search:
String searchTerm = "E1";
for (Employee employe : employeeArr) {
if (employe.getId() == searchTerm) {
System.out.println("Employe_ID: E" + employe.getEmployeId() +
"\narbetstitel: " + employe.getArbetsTitel());
}
}
Better yet, use a HashMap so you don't have to loop to find an employee:
HashMap<String, Employee> employees = new HashMap<>(); // String to store IDs
Employee e = new Employee();
employees.put("E1", e);
// To fetch an employee
Employee e1 = employees.get("E1");
if (e1 != null) {
System.out.println("Employe_ID: E" + e1.getEmployeId() +
"\narbetstitel: " + e1.getArbetsTitel());
}
I'm new to Java and I'm trying to get my head around constructs, classes and objects. I apologise if any of this seems stupid to you.
I have been tasked with creating an ArrayList to hold items of type Data (my class). using the .add method - I should add a certain number of names and ages then output.
I have sort of done it, but I was wondering if I could use the functions like SetAge and SetAge from my class to use within my ArrayList to create a new person and then output it together like I have with the rest. Is there another way?
Thank you for your help & explanation.
Below is my code;
import java.util.ArrayList;
public class workingOn {
public static void main (String[] args)
{
Data Fred = new Data("Fred", 21);
Data Jo = new Data("Jo", 43);
Data Zoe = new Data("Zoe", 37);
ArrayList<Data> myArray = new ArrayList<Data>();
myArray.add(Fred);
myArray.add(Jo);
myArray.add(Zoe);
for (Data temp : myArray)
{
System.out.println(temp.toString());
}
}
}
Below is my class;
public class Data {
private String name;
private int age;
Data(String n,int a)
{
name = n;
age = a;
}
public String GetName()
{
return(name);
}
public void SetName(String n)
{
name = n;
}
public int GetAge()
{
return(age);
}
public void SetAge(int a)
{
age = a;
}
public void Print()
{
System.out.print(("("+ GetName() ));
System.out.print(",");
System.out.print(GetAge());
System.out.print(") ");
}
//i made this so I don't output the object id
public String toString() {
return (name + ", " + age);
}
}
Going through the comments, I am guessing you want to somehow use the setter methods (setName() and setAge()) for the class that you have designed. The easiest way would be:
Data d = new Data("tempName", 10);
myArray.add(d);
This basically creates an object of type Data and adds it to the arraylist. Let's assume that you want to change the name and age of this person you just added, then you should do this:
myArray.get(myArray.size() - 1).setName("newName");
myArray.get(myArray.size() - 1).setAge(18);
To add some explanation, when you add an object to an arraylist, it always adds in the end. We use size() method to get the number of objects in the Arraylist. Since index starts from 0, we use myArray.size() - 1. We use the .get() method to retrieve the object from the arraylist which takes a number as a parameter and return the object at that index.
Combining these two, we get the object at the last possible index, and call the setName() and setAge() function on it.
Hope this helps.
My program asks the user to enter the first name, last name and age of 5 people and stores them in an array. I want to write a method that asks the user whom they want to delete from the array and then deletes that employee. I know in arrays you cannot technically delete an object from an array, just replace it.
This is what I've done so far:
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employees[i].getFirstName().equals(name)){
employees[i] = employees[employees.length - 1];
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}
My problem is that it does not decreases the array size by 1, it just replaces the person I want to delete with the last person in my array. My output has the last employee in the array repeated twice (in it's last index and in the index of the person I wanted to delete) How do I fix this?
you can replace the employee with null whenever want to delete it. when inserting a new emplyee, you can first look at a null index and place it.
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employee[i] != null && employees[i].getFirstName().equals(name)){
employees[i] = null;
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}
You may want to use ArrayLists for this problem. ArrayLists are Java's way of creating a mutable array. With arraylists, the array can be automatically expanded and reduced based on the number of objects in the Array.
You can add and delete objects using the index or variable name.
Sample Code:
ArrayList<Employee> employees = new ArrayList<>;
Then you can use the following methods:
employees.remove(int index);
employees.remove(Object o);
Check this out for more reference: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
One possibility: although you can't change the actual length of the array, you can use another variable to keep track of the "real" length (i.e. the number of elements in the array that you know are valid):
int currentLength = employees.length;
for (int i = 0; i < currentLength; i++) {
if (employees[i].getFirstName().equals(name)){
employees[i] = employees[currentLength - 1];
// employees[currentLength - 1] = null; ... could help reclaim storage
currentLength--;
break;
}
if (i == currentLength - 1) {
System.out.println("That requested person is not employed at this firm.")
}
The program just "knows" that array elements from employees[currentLength] through employees[employees.length - 1] aren't meaningful. You could also set those meaningless elements to null so that there aren't unused references that could prevent some objects from being garbage-collected (this would be important in a larger program). This approach can be a bit error-prone, because you have to remember to use currentLength instead of employees.length. Overall, I think it's better to use an ArrayList, which has a way to delete elements.
The length of an array in Java can not be changed, it's initialized when you create it.
And you can not manual delete a element immediately(like C++). You can set it to null, then wait for the JVM to recycle it.
For convenience, you can use List collection in java.util package. They are convenient for remove/add elements.
I suggest you make use of ArrayList, it already had the remove method. That method also make the size of the list reduce by number of removed items
Hi things will be simpler for you if you use an ArrayList instead of an array, Here is how your code will look like assuming that you have a EmployerClass implementing the getFirstName() method
List<EmployerClass> employees = new ArrayList<EmployerClass>();
// Here is the new type of your employees pool
....
// do whatever you want to put employees in the poll using employees.add(...)
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
EmployerClass tmpEmployer = null;
for(EmployerClass emp : employees) {
if(emp.getFirstName().equals(name)) {
break;
}
}
if(tmpEmployer != null){
// remove the employee to the pool
employees.remove(tmpEmployer);
} else {
System.out.println("That requested person is not employed at this firm.");
}
}
good luck !
You can't really delete it, but you can only make it null.
ArrayList or LinkedList is better for this task. In both you can use builtin methods to add or remove elements and size is handle automatically.
There are some points:
(1) Java array(use the symbol "[]") is a fixed size structure. It means you must specify the size(length) of the array when you create it. Like this:
int[] intArray = new int[10];
The purpose of the specific size is to tell Java compiler to allocate memory. Array is allocated in contiguous memory. Once the allocation has been done, its size could not be changed.(You can image there are other data "behind" the array, if the array is extende, will overlap the other data.)
(2) If you want to get a flexible data collection, for your adding/removing, you can use ArrayList or LinkedList. These Java built-in collections can be extended by themselves if needed.
What's more:
ArrayList is implemented by Java array, it will automatically create a new larger array and copy the data into it when its Capacity is not enough. It has good performance in loop, access elements by index.
LinkedList is implemented by Linked List. It has good performance in insert/remove elements.
For Both lists, if you want to use the remove(Object o) correctly, you have to implement your object's public boolean equals(Object) function.
Ref to the code:
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListTest {
public static void main(String[] args) {
List<Employee> employees = new LinkedList<Employee>();
// List<Employee> employees = new ArrayList<Employee>();
// Add 3 employees
employees.add(new Employee("Tom", "White", 10));
employees.add(new Employee("Mary", "Black", 20));
employees.add(new Employee("Jack", "Brown", 30));
// See what are in the list
System.out.println(employees);
// Remove the 2nd one.
employees.remove(new Employee("Mary", "Black", 20));
// See what are in the list after removing.
System.out.println(employees);
}
static class Employee {
private String firstName;
private String lastName;
private int age;
public Employee(String firstName, String lastName, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public boolean equals(Object obj) {
if(super.equals(obj)) {
return true;
}
else {
if(obj.getClass() == Employee.class) {
Employee that = (Employee)obj;
return firstName.equals(that.getFirstName()) && lastName.equals(that.getLastName()) && (age == that.getAge());
}
else {
return false;
}
}
}
#Override
public String toString() {
return "Employee [firstName=" + firstName + ", lastName="
+ lastName + ", age=" + age + "]\n";
}
}
}
I currently have a working GUI program that has a few buttons on it to simply step through my arraylist of items. These simply display the first, last or next and previous index results. This list has String, int and double inside of it. Now I have added a JTextField for input and a search button. My question is how do I get my search button to search through this array list? I was reading this answer but I don't understand the datum thing. Do I have to convert the entire arraylist to string before searching through it? Would something like
ArrayList<inventoryItem> inventory = new ArrayList<>(); ....
JTextField input = new JTextField(18); ...
JButton searchButton = new JButton("Search");
searchButton.setToolTipText("Search for entry");
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (String s : inventory) {
if (usrInput.contains(s)) {
inventory.get(currentIndex);
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
The error I get is that inventoryItem cannot be converted to string. The second problem: I am having is how to I make it output everything in that index. For example my output looks like this:
class officeSupplyItem extends inventoryItem {
public officeSupplyItem(String itemName, int itemNumber, int inStock, double unitPrice) {
super(itemName, itemNumber, inStock, unitPrice);
}
#Override
public void output(JTextArea outputText) {
outputText.setText("Item Name = " + itemName + " \n"); //print out the item name
outputText.append("Item Number = " + itemNumber + " \n"); //print out the item number
outputText.append("In Stock = " + inStock + " \n"); //print out how many of the item are in stock
outputText.append("Item Price = $" + formatted.format(unitPrice) + " \n"); //print out the price per item
outputText.append("Restocking fee is $" + formatted.format(restockingFee) + " per item \n");
outputText.append("Value of item inventory = $" + formatted.format(value) + " \n"); //print out the value of the item inventory
outputText.append("Cost of inventory w/restocking fee = $" + formatted.format(inventoryValue) + " \n"); //print out the total cost of inventory with restocking fee
}
}
I would also like to understand what the datum portion of the mentioned link means.
I am not quite clear on what you mean by "This list has String, int and double inside of it".
You are comparing an object field with the text entered. You need not convert InventoryItem to a string. What you need to do is identify which fields you want to compare and use them in the comparison.
From what I see the text being entered to the JTextField is the search criteria for your code. If I assume it to be itemName, your code should be as follows :
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem s : inventory) {
if (usrInput.equalsIgnoreCase(s.getItemName())) {
//you can call output string here
outputText.append(" somehow put whatever the index is equal to here");
}
}
}
});
This is for the case if the JTextField input is the itemName. If this is any different than you expect, please comment.
From the link you shared, the difference is that his List contains only Strings, that is why "datum" is a String. This cannot be used for your case.
Hope this helps!
As per my understanding, what ever the searchText is (itemName or itemNumber) the results should be listed. Therefore, you could write a search method that compares and returns whether it matches the search string as follows in the InventoryItem class.
public boolean isSearchTextAvailable(String searchText) {
if (this.itemName.equals(searchText)) {
return true;
} else {
try {
int no = Integer.parseInt(searchText);
if (this.itemNumber == no) {
return true;
}
} catch (NumberFormatException e) {
System.out.println("Not a integer");
}
}
return false;
}
You can enhance this method to any number of fields you want to be searched within.
Then use this method in the action for the searchButton.
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (InventoryItem invItem : inventory) {
if (invItem.isSearchTextAvailable(usrInput)) {
invItem.output(outputText);
}
}
}
});
You have to make input (JTextField) a field in this class to make it work.
Few tips to increase quality of your code:
Separate InventoryItem and OfficeSupplyItem classes to different files
Notice the naming convention for class names is PascalCase
Better to have JavaGUIFixed class extended from JFrame and all its components defined as fields and not local variables since you use them in various other methods other than makeWindow() method where you actually create the JFrame
Do not use invItem.output(outputText) type of methods, where you pass a JTextField to a object Method to write to it. What you could do instead is write a method like getOutputString() in InventoryItem class which will return a formatted string of what needs to be printed and then call outputText.setText(invItem.getOutputString()) - Your implementation is restricting you to have all classes as inner classes to JavaGUIFixed.
Hope this helps!
Your enhanced for loop is saying for each String element s in ArrayList inventory... But inventory is declared to be an ArrayList of inventoryItem objects, not a list of strings, and the for loop isn't accessing the variables where the values you are trying to search are stored, as each index of inventory is just storing a reference to an object.
If your main goal is taking input, storing, sorting, and outputting it, you might consider taking and storing it as strings in a string collection. You can always parse to int or double if you need to at some point, but it will be easier to sort and search with a homogenous data type.
Where I saw datum used in that link was just as a variable name, the same way you used 's' in your code.
I have marked #maheeka 's response as the answer. I however had to modify his code because of the way that I had previously written my program. It now looks as follows:
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
String usrInput = input.getText();
for (int i = 0; i < inventory.size(); i++) {
if (usrInput.equalsIgnoreCase(inventory.get(i).getItemName())) {
currentIndex = i;
displayItem(outputText);
I also had to set up my getter on the itemName as I apparently had forgotten that part. Thank you #Aadi Droid for that.
I am trying to get this program to get the passwords from an array list.
import java.util.ArrayList;
public class CompanyDatabase {
public ArrayList<Person> getPeople() {
ArrayList<Person> people = new ArrayList<Person>();
String[] u = {"Joe","Stan","Leo","John","Sara","Lauren"};
String[] p = {"pass4321", "asdfjkl", "genericpw", "13579", "helloworld", "companypass"};
for(int j = 0; j < u.length; j++){
Person temp = new Person(u[j],p[j]);
people.add(temp);
}
return people;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class CompanyDatabaseDriver {
private static Scanner scan = new Scanner( System.in ) );
public static void main(String args[]) {
CompanyDatabase bcData = new CompanyDatabase();
ArrayList<Person> people = bcData.getPeople();
// what i tried
System.out.println(bcData.getPeople());
// also tried this
System.out.println(people.get(1));
}
}
The output is
[Person#1c9b9ca, Person#c4aad3, Person#1ab28fe, Person#105738, Person#ce5b1c, Person#1bfc93a]
or just
Person#1995d80
for the 2nd thing I tried.
The specific number / letter combination seems to change each time the program is run. Is there a way to specify which string to display from the array list?
Override toString() in the Person class
What you are seeing is the String returned by Object's default toString() method which is the name of the class followed by its hashcode. You will want to override this method and give the Person class a decent toString() method override.
e.g.,
// assuming Person has a name and a password field
#Override
public String toString() {
return name + ": " + password; // + other field contents?
}
Edit: if you only want to display one field in your output, then use Dave Newton's good solution (1+).
Yes; print the object property you want to see:
out.println(people.get(0).getFirstName());
the default implementation when you print List is to call toString for all objects in this List. and because you don't override toString method, it will call the default toString from Object class, that will print objects hashCode in hexadecimal notation, so you get this result:
Person#1c9b9ca ( classname#hashcode) , and it can be changed every time you execute the application because this hashcode come from memory address of the object).
so one option, is to override toString in your class
#Override
public String toString() {
return String.format("First name %s, Last name %s", firstName, lastName);
}
and call
System.out.println(yourList); // this will print toString for each object
the other option, is to print these attributes when you iterate on the List
for(Person person: persons) {
System.out.println("Person first name: " + person.getFirstName() + " , Last Name: " + person.getLastName());
}
In the first print statement you are trying to print the object..that is why you always see different number/letter combination..