Hello guys maybe my doubt is simple but could not solve.
My question is as follows:
I have an ArrayList of objects, these objects have number, name and value.
I would like to sum the values of these objects when the number and name are the same.
I thought of creating a new ArrayList to go the added values sum but to no avail.
My class:
private class ItemAdubacao {
float quantidadeProduto;
String produto;
int tanque_id;
public float getQuantidadeProduto() {
return quantidadeProduto;
}
public void setQuantidadeProduto(float quantidadeProduto) {
this.quantidadeProduto = quantidadeProduto;
}
public String getProduto() {
return produto;
}
public void setProduto(String produto) {
this.produto = produto;
}
public int getTanque_id() {
return tanque_id;
}
public void setTanque_id(int tanque_id) {
this.tanque_id = tanque_id;
}
}
I'm adding objects of this class in an ArrayList.
What I want is to go through this ArrayList checking objects that have Tanque_id and produto equal to sum the quantidadeProduto.
As I said I thought I'd create a new ArrayList and go adding the objects already added. For example:
public void finalizar() {
Adubacao adubacao = new Adubacao();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if () {
}
}
adubacaoArrayList.add(adubacao);
}
But do not know how to IF
I solved my question, is not simple question IF
first added boolean equals in my class
public boolean equals(Object o) {
ItemAdubacao adubacao = (ItemAdubacao) o;
if (this.getTanque_id() == adubacao.getTanque_id() && (this.getProduto().equals(adubacao.getProduto()))) {
return true;
}
return false;
}
then I created an ArrayList to separate the duplicate objects and adding the sum of values
public void finalizar() {
ArrayList<ItemAdubacao> itensIguaisArrayList;
itensIguaisArrayList = new ArrayList<>();
adubacaoArrayList = new ArrayList<>();
for (ItemAdubacao itemAdubacao : itemAdubacaoArrayList) {
if (!itensIguaisArrayList.contains(itemAdubacao)) {
itensIguaisArrayList.add(itemAdubacao);
}
}
for (int i = 0; i < itensIguaisArrayList.size(); i++) {
float soma = 0;
for (ItemAdubacao linha : itemAdubacaoArrayList) {
if (linha.equals(itensIguaisArrayList.get(i))) {
soma += linha.getQuantidadeProduto();
}
}
itensIguaisArrayList.get(i).setQuantidadeProduto(soma);
}
}
Related
I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work
I am new to programming and we just learned ArrayLists in my class today and I have an easy question for you guys, I just can't seem to find it in the notes on what to set the passing value equal to. The point of this practice program is to take in a Number Object (that class has already been created) and those Numbers in the ArrayList are supposed to be counted as odds, evens, and perfect numbers. Here is the first couple of lines of the program which is all you should need.
import java.util.ArrayList;
import static java.lang.System.*;
public class NumberAnalyzer {
private ArrayList<Number> list;
public NumberAnalyzer() {
list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
}
public void setList(String numbers) {
}
What am I supposed to set (String numbers) to in both NumberAnalyzer() and setList()? Thanks in advance for answering a noob question!
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
This is the Lab16b Class that will run the program. ^^
public class Number
{
private Integer number;
public Number()
{
number = 0;
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return 0;
}
public boolean isOdd()
{
return number % 2 != 0;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++)
{
if(number % i == 0)
{
total = total + i;
}
}
if(total == number)
{
return true;
}
else
{
return false;
}
}
public String toString( )
{
return "";
}
}
Here is the Number class. ^^
Based on the information you provided, this is what I feel NumberAnalyzer should look like. The setList function is presently being used to take a String and add the numbers in it to a new list.
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer() {
this.list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
setList(numbers);
}
public void setList(String numbers) {
String[] nums = numbers.split(" ");
this.list = new ArrayList<Number>();
for(String num: nums)
list.add(new Number(Integer.parseInt(num)));
}
}
Analyze to learn something.
public static void main(String[] args) {
String temp = "5 12 9 6 1 4 8 6";
NumberAnalyzer analyzer = new NumberAnalyzer(temp);
//foreach without lambda expressions
System.out.println("without Lambda");
for (NeverNumber i : analyzer.getList()) {
i.print();
}
//with the use of lambda expressions, which was introduced in Java 8
System.out.println("\nwith Lambda");
analyzer.getList().stream().forEach((noNumber) -> noNumber.print());
NeverNumber number = new NeverNumber(31);
number.print();
number.setNumber(1234);
number.print();
}
public class NumberAnalyzer {
private List<NeverNumber> list; //List is interface for ArrayList
public NumberAnalyzer(String numbers) {
String[] numb=numbers.split(" ");
this.list=new ArrayList<>();
for (String i : numb) {
list.add(new NeverNumber(Integer.parseInt(i)));
}
}
public void setList(List<NeverNumber> numbers) {
List<NeverNumber> copy=new ArrayList<>();
numbers.stream().forEach((i) -> {
copy.add(i.copy());
});
this.list=copy;
}
public List<NeverNumber> getList() {
List<NeverNumber> copy=new ArrayList<>();
this.list.stream().forEach((i) -> {
copy.add(i.copy());
});
return copy;
}
public NeverNumber getNumber(int index) {
return list.get(index).copy();
}
}
public class NeverNumber { //We do not use the names used in the standard library.
//In the library there is a class Number.
private int number; // If you can use simple types int instead of Integer.
public NeverNumber() {
number = 0;
}
public NeverNumber(int num) {
number = num;
}
private NeverNumber(NeverNumber nn) {
this.number=nn.number;
}
public void setNumber(int num) {
number = num;
}
public int getNumber() {
return this.number;
}
public boolean isOdd() {
return number % 2 != 0;
}
public boolean isPerfect() {
long end = Math.round(Math.sqrt(number)); //Method Math.sqrt(Number) returns a double, a method Math.round(double) returns long.
for (int i = 2; i < end + 1; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public NeverNumber copy(){
return new NeverNumber(this);
}
public void print() {
System.out.println("for: " + this.toString() + " isPer: " + this.isPerfect() + " isOdd: " + this.isOdd() + "\n");
}
#Override //Every class in Java inherits from the Object class in which it is toString(),
//so we have to override our implementation.
public String toString() {
return this.number + ""; //The object of any class + "" creates a new object of the String class,
//that is for complex types, calls the toString () method implemented in this class,
//override the toString () from the Object class. If the runs, we miss class toString()
//calls from the Object class.
}
}
Struggling with a little project I've set myself to learn Java. My goal is to create a program to store a list of Car objects. Then to allow the user to search for a particular car and output all of them if they exist. The car object should contain model name, registration number, vin and colour. Here is what I have so far:
package carObjects;
public class cars {
public static int length;
private String modelName;
private String carColour;
private int regNumber;
private int vin;
public cars(String string, String string2, int i) {
}
public String toString() {
return "Model Name: " + modelName + "Registration Number: " + regNumber
+ "Vin" + vin + "Car Colour: " + carColour;
}
public String getLast() {
return modelName;
}
}
for (int i = 0; i < cars.length; i++) {
cars[i] = new cars("A", "B", 10);
}
for (cars p : cars) {
System.out.println(p.getLast());
}
}
}
Here are some of the things you would need to do:
Since you want to allow searching, you will need to expose accessors to the properties which you would like the user to search for. For instance, if you want to allow users to search by model, you will need to expose the model property. You seem to be doing this through the getLast() method, however, the name is confusing.*
The problem with this code: for (int i = 0; i < cars.length; i++) {
cars[i] = new cars("A", "B", 10);
}
Is that it is creating a series of identical objects. You could use the value of i to provide some dummy, changing values. This will allow you to test that your search is indeed working.
Constructor names should start with an upper case, just like class names.
cars(String string, String string2, int i): Please provide meaningful names to your variables. This will make your code easier to read.
You will need to assign the variables you are getting through your constructor. As is, at the moment your fields will not be initialized to what you are providing.
To create a 2D array, you will need to use the following syntax: Car[][] carArr = new Car[5][5]. This will create a 5x5 array of type car. To iterate over it, you will need to use a nested loop:
for(int i = 0; i < carrArr.length; i++) {
for (int j = 0; j < carrArr[i].lenght;j++) {
...
}
}
* The usage of getters and setters allow you to control which object properties are exposed and how can users interact with them.
The best would be to separate your exercise in two different classes:
class Car {
private String modelName;
private String carColour;
private int regNumber;
private int vin;
public int getVin() {
return vin;
}
public void setVin(int vin) {
this.vin = vin;
}
// other getter/setter
#Override
public String toString() {
return "Car: " + getVin();
}
#Override
public int hashCode() {
return vin;
}
#Override
public boolean equals(Object obj) {
return (obj != null)
&& (obj instanceof Car)
&& ((Car) obj).getVin() == this.getVin();
}
}
CarSet class has the searching methods:
class CarList extends HashSet<Car> {
public Car serarchByVin(int vin) {
List<Car> list = new ArrayList<>(this);
for (Car c : list) {
if (c.getVin() == vin) {
return c;
}
}
return null;
}
public CarSet searchByModel(String model) {
CarSet result = new CarSet();
List<Car> list = new ArrayList<>(this);
for (Car c : list) {
if (c.getModelName()== model) {
result.add(c);
}
}
return result;
}
#Override
public String toString() {
String result = "carList: ";
for (Car c : this) {
result += c;
}
return result;
}
}
I have a question. I cant solve it and I need some help please. I have an Arraylist of objects then I have a method where objects are created and added to the Arraylist but I want another method where I can print the Arraylist but everytime I try the Arraylist is empty so this is my code:
public class Packages{
ArrayList<Pack> myList = new ArrayList<Pack>();
Pack obj;
public double addPackage(int type, double num){
if(type==1)
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
else
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
myList.add(obj);
return total;
}
public int listSize(){
return myList.size();
}
}
Everytime I call the listSize() method it returns 0, looks like when the addPackage method finishes it deletes the objects I added to my Arraylist.
Note: my addPackage method is going to return a double total but at the same time add the objects I create to the arraylist. I need some help please.
I tried your code and it is almost right. I am posting the classes again which I used and which work:
public class Package {
List<Pack> myList = new ArrayList<Pack>();
Pack obj;
double total = 0;
public double addPackage(int type, double num) {
if (type == 1) {
obj = new Pack(type, num);
total = obj.calculateTotal();
} else {
obj = new Pack(type, num);
total = obj.calculateTotal();
}
myList.add(obj);
return total;
}
public int listSize() {
return myList.size();
}
}
Now class Pack is:
public class Pack {
int type;
double value;
public Pack(int type, double value) {
this.type = type;
this.value = value;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double calculateTotal() {
return type*value;
}
}
And I verified in this code:
public static void main(String[] args) {
Package pkg = new Package();
pkg.addPackage(10,10);
pkg.addPackage(10,20);
System.out.println(pkg.listSize());
}
And as expected it returns 2. All these classes may not exactly be same as what you have but it will give you the idea about what are you missing.
I have an ArrayList made out of classes objects .The class has several String fields . In some classes
some fields that are the same must be removed from the ArrayList .
The field from the class that I need to check is sorted_participants which is set to be the same in some objects.
This is my Class:
public class Neo4jCompensation {
private String number_of_participants;
private String amount;
private String sorted_participants;
private String unsorted_participants;
private String href_pdf_compensation;
private String signed_by_all;
public Neo4jCompensation() {
this.number_of_participants = "";
this.amount = "";
this.sorted_participants = "";
this.unsorted_participants = "";
this.href_pdf_compensation = "";
this.signed_by_all = "";
}
public String getNumber_of_participants() {
return number_of_participants;
}
public void setNumber_of_participants(String number_of_participants) {
this.number_of_participants = number_of_participants;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getSorted_participants() {
return sorted_participants;
}
public void setSorted_participants(String sorted_participants) {
this.sorted_participants = sorted_participants;
}
public String getUnsorted_participants() {
return unsorted_participants;
}
public void setUnsorted_participants(String unsorted_participants) {
this.unsorted_participants = unsorted_participants;
}
public String getHref_pdf_compensation() {
return href_pdf_compensation;
}
public void setHref_pdf_compensation(String href_pdf_compensation) {
this.href_pdf_compensation = href_pdf_compensation;
}
public String getSigned_by_all() {
return signed_by_all;
}
public void setSigned_by_all(String signed_by_all) {
this.signed_by_all = signed_by_all;
}
}
So I have a first list filled with Classes:
ArrayList<Neo4jCompensation> results_list=new ArrayList<Neo4jCompensation>();
I thought that very good way to find the duplicates is to make a copy of a list , compare the two for the same class fields values and remove the duplicates .
This is how I find the duplicates
ArrayList<Neo4jCompensation> results_list1=new ArrayList<Neo4jCompensation>();
for(Neo4jCompensation pp:results_list)
{
Neo4jCompensation ss=new Neo4jCompensation();
ss.setAmount(pp.getAmount());
ss.setHref_pdf_compensation(pp.getHref_pdf_compensation());
ss.setNumber_of_participants(pp.getNumber_of_participants());
ss.setSigned_by_all(pp.getSigned_by_all());
ss.setSorted_participants(pp.getSorted_participants());
ss.setUnsorted_participants(pp.getUnsorted_participants());
results_list1.add(ss);
}
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(i!=j)
{
String prvi=kk.getSorted_participants().trim();
String drugi=n2.getSorted_participants().trim();
if(prvi.equals(drugi))
{
// results_list1.remove(j);
out.println("<p> Are equal su :"+i+" i "+j+"</p>");
}
}
}
}
Since I know that I can not loop and remove the elements from the ArrayList at the same
time i tried to use iterators like this ...
int one=0;
int two=0;
Iterator<Neo4jCompensation> it = results_list.iterator();
while (it.hasNext()) {
Neo4jCompensation kk=it.next();
Iterator<Neo4jCompensation> it1 = results_list1.iterator();
while (it1.hasNext()) {
Neo4jCompensation kk1=it1.next();
String oo=kk.getSorted_participants().trim();
String pp=kk1.getSorted_participants().trim();
if(one<two && oo.equals(pp))
{
it1.remove();
}
two++;
}
one++;
}
But it fails and gives me back nothing in ArrayList results_list1 - before removal with iterator it has in it the right elements . How to remove the objects from the array list that have the same field values as some other objects in the ArrayList .
Why not use .removeAll()
results_list1.removeAll(resultList);
This will require you to implement equals and hashcode within Neo4jCompensation
public class Neo4jCompensation {
//Omitted Code
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((number_of_participants == null) ? 0
: number_of_participants.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Neo4jCompensation other = (Neo4jCompensation) obj;
if (number_of_participants == null) {
if (other.number_of_participants != null)
return false;
} else if (!number_of_participants.equals(other.number_of_participants))
return false;
return true;
}
}
Another approach could be:
Overrride equals method in your Neo4jCompensation and check for the sorted_participants and return accordingly. Then use Set as a collection of your objects. Set does not allow duplicates and it uses equals to determine the equality.
for (int i = 0; i < results_list.size(); i++) {
Neo4jCompensation kk=new Neo4jCompensation();
kk=results_list.get(i);
for (int j = 0; j < results_list1.size(); j++) {
Neo4jCompensation n2=new Neo4jCompensation();
n2=results_list1.get(j);
if(results_list1.contains(kk) { results_list1.remove(j); }
}
But you may want to use a Set instead of a List or a data structure that maintains order, like a SortedMap, with a sentinel value.