This question already has answers here:
Check if a value exists in ArrayList
(4 answers)
Closed 2 years ago.
I am trying to loop through an ArrayList, and compare each index value to a default value, if the index value matches the default value, I want to return true, the only problem is that, it always returns true only to the index item that is added. Since my class doesn't have a main method, I have added those values during the class constructor initialization.
public class CountryFinderImpl implements CountryFinder{
List<String> Countries = new ArrayList<String>();
public CountryFinderImpl() {
Countries.add("canada");
Countries.add("japan");
Countries.add("usa");
}
#Override
public boolean forWeather(String country) {
// TODO Auto-generated method stub
country = country.toLowerCase();
boolean c=false;
for(int i=0; i<Countries.size();i++) {
if(Countries.get(i).equals(country)) {
//System.out.println(country+"Weather available");
c=true;
}else {
//System.out.println(country+"weather unavilable");
c=false;
}
}
return c;
}
}
The country parameter is passed from another class, which takes the country value from the user.
In each iteration of the loop, you overwrite c, regardless of its value, so you'll always return the result fot the last element. One solution is to use the "early return" idiom and return true immediatly when the item is found:
#Override
public boolean forWeather(String country) {
country = country.toLowerCase();
for (int i = 0; i < Countries.size() ;i++) {
if (Countries.get(i).equals(country)) {
return true;
}
}
return false;
}
Note, however, that this is just a reimplementation of the contains method, so you might as well just use it:
#Override
public boolean forWeather(String country) {
return Countries.contains(country.toLowerCase());
}
Related
This question already has answers here:
Remove specific index from array in java
(6 answers)
Why we need to override hashCode and equals?
(4 answers)
Closed 5 years ago.
I have created an array of objects (object representing a flight),
and i'm trying to create a method to remove a specific object from that array, without changing it's length.
I have written the following method :
public boolean removeFlight (Flight f) {
for (int i = 0 ; i < _noOfFlights ; i++) {
if (_flightsSchedule[i].equals(f)) {
_flightsSchedule[i] = _flightsSchedule[(i+1)];
_noOfFlights--;
return true;
}
}
return false;
}
_noOfFlights represents the number of object currently in the array.
For some reason it returns "false" when given an object that was added to the array.
You need to be careful not to change the ground under your feet. You also don't want to return in the middle of the loop, otherwise you won't have moved all the elements properly.
You could do something like this:
public boolean removeFlight (Flight f) {
boolean found = false;
for (int i = 0 ; i < _flightsSchedule.length; i++) {
if (f.equals(_flightsSchedule[i])) {
found = true;
} else if (found) {
_flightsSchedule[i - 1] = _flightsSchedule[i];
}
}
if (found) {
_noOfFlights--;
_flightsSchedule[_flightsSchedule.length - 1] = null;
}
return found;
}
Also, note that I've set the last element to null to avoid an inadvertent memory leak.
I need help with removing just added element from the arrayList.
I have a private static ArrayList<Position> positions = new ArrayList<>() to which I'm adding objects of the class Position with parameters name, quantity, and price.
Than I have a method adding objects to the list, and in case if the same product is added for the second time, it is supposed to add the quantity to the first object of that name and remove that second one.
So far I have this method:
public void addPosition(Position p) {
for (Position poz: positions) {
if (poz.getname().equals(p.getname())) {
poz.setquantity(poz.getquantity() + p.getquantity());
}
} positions.add(p);
}
Adding quantities works just fine, but I've got problem with removing the element with recurring name.
Please help.
You shouldn't add duplicate items and then remove them. Just declare a method which handles adding items correctly; that is, it adds the item if it does not exist, and it updates the quantity if it does exist.
It should look like this:
public void addPosition(Position addition) {
//flag to track whether the new item exists in the list
boolean itemExists = false;
//go through the list looking for an item with the passed name to update
for (Position existing : positions) {
if (existing.getName().equals(addition.getName())) {
existing.setQuantity(existing.getQuantity() + addition.getQuantity());
itemExists = true;
}
}
//if no matching item was found, add the new item
if (!itemExists) {
positions.add(addition);
}
}
The above should work. If you care about performance, it might be better to use a HashMap so you can look up the Position by name instead of looping through the whole list each time.
If you are interested to know other data Structure , i want suggest you HashSet , by default it will not insert duplicates for primitive objects .
In your case the only thing you need to do to your Position class , is to add
equals and hashCode methods . As getters and setters Eclipse for example will create by him self .
hashCode()
As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode(); It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.
equals()
This particular method is used to make equal comparison between two objects. There are two types of comparisons in Java. One is using “= =” operator and another is “equals()”. I hope that you know the difference between this two. More specifically the “.equals()” refers to equivalence relations. So in broad sense you say that two objects are equivalent they satisfy the “equals()” condition. If you look into the source code of Object class you will find the following code for the equals() method.
Here a complete working example ( you can modify your class following this cose)
import java.util.HashSet;
public class Zhashset{
private int num;
public Zhashset(){
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + num;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Zhashset other = (Zhashset) obj;
if (num != other.num)
return false;
return true;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Zhashset> hs = new HashSet<Zhashset>();
hs.add(new Zhashset());
hs.add(new Zhashset());
for(Zhashset item : hs)
System.out.println(item.getNum());
}
}
Output will be : 0 written only once.
For my data structures class, we have to create our own Stack data type and the implementation for it as a project. The problem I'm running into is when the professor asked us to implement an equals(Object object) method. Heres what I have so far...
package stack;
import list.*;
public class Stack <E>
implements StackADT<E>//the interface
{
List <E> values;
public Stack()
{
values = new ArrayList<E>();
}
public E push(E value)
{
values.add(value);
return value;
}
public E pop()
{
return values.remove(values.size()-1);
}
public E peek()
{
return values.get(values.size()-1);
}
/** #return true only if this Stack is empty */
public boolean isEmpty()
{
return (values.size()==0);
}
/** Clear this stack, to make it an empty stack */
public void clear()
{
for (int i = 0; i < values.size()-1; i++)
{
pop();
}
}
public String toString()
{
String result = "[";
for (int i = 0; i<values.size(); i++)
{
if (i == values.size()-1)
{
result = result + values.get(i);
}
else
{
result = result + values.get(i) +",";
}
}
result = result + "]";
return result;
}
public boolean equals (Object object)
{
if (!(object instanceof StackADT))
{
return false;
}
StackADT <E> otherStack = new Stack<E>();
for(Object o: object)//heres where i run into trouble
{
otherStack.push(o);
}
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
}
Our Stack is pretty much an ArrayList which we also built in our class. the problem is, I cant add the Object object into a stack because its not something thats iteratable(?able to be iterated over). Is there a better way to do this? I would think a get() would work, since the Stack I create is an ArrayList, but whenever I use get() on otherStack, it can't find the method. I had a temporary solution when I tried casting object as a stack(I hope im using the right terminology). It looked something like this
Stack otherStack = (Stack) object;
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
this seemed to work, but when pop() was called on otherStack, the values in the original list(the one that becomes otherStack) that was passed into the equals() method we're also popped from the original list, leading to an incorrect result. Is there a better way to do this without adding in any other methods? I'm trying to stick as close to the formula set up by my professor as possible, so I dont want to add any extra fields or methods.
any and all help is appreciated
An equals method is not supposed to create anything, not even a temporary object. Rather than creating a new otherStack, cast the object that you have checked to be StackADT, like this:
// This should be the first line of any equals() implementation:
if (object == this) {
return true;
}
// You've got this part right: you need to check the other object's type
if (!(object instanceof StackADT)) {
return false;
}
// Now that you know the type, cast the other object to StackADT<E>
StackADT<E> otherStack = (StackADT<E>)object;
// The next step is to check the sizes:
if (values.size() != otherStack.values.size()) {
return false;
}
// Finally, go through the individual elements in a loop
In the loop that follows, do not pop the other stack. Do not do anything that can modify it. Simply go through the underlying storage (i.e. values), and check elements one by one.
Don't forget to override hashCode as well: you need to do it every time when you override equals for the object to fulfill the contract specified by java.lang.Object.
I have an issue where I am trying to compare an object's name (String) to another String, and I've tried using .equals() as well as == but neither seem to work in my case.
The code I have right now is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
else
{
return false;
}
}
}
The program always returns false, even if the name that has been set to product[i] is the same as the parameter given. I've tried looking at other questions relating to .equals() and == and other String references but I have not had any luck in finding something that relates to my problem.
I have seen people use compareTo(), but I'm not sure if that is necessary in my code, and I'm not completely sure on how to use it.
EDIT: As said by Houssni in the comments, I have just realised that the return statement ends the loop and method. Is it possible to check each product's name without having the method terminated after the first check, and have it return a boolean value?
EDIT 2: I have modified the code to how the answers that have been provided say, which is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
I still get the same issue with the product[i].getName() not being equal to checkName and the method returning false, even though they should equal. Any possibilities on why this is happening, because I've looked through my code and I'm not sure.
Edit 3: The only other code that relates to the block of code above is the input of the parameter from another class, which is:
String checkName = JOptionPane.showInputDialog("Enter the name: ");
while (storingProducts.checkingObjectName(checkName) == false) //assume for storingProducts
{
JOptionPane.showMessageDialog(null, "No products were found. Please re-input name.");
checkName = JOptionPane.showInputDialog("Enter the name: ");
storingProducts.checkingObjectName(checkName);
}
if (storingProducts.checkingObjectName(checkName) == true)
//extra code
So, that's all the code relating to my issue. I'm still not sure why the method returns false, though both values are receiving the same String value.
Edit 4: The product and count are coming from the class with the checkingObjectName method:
public class Store
{
private Product[] product; //Product is another class that just sets and gets
private int count=3;
public Store()
{
product = new Product[count];
for (int i=0; i<count; i++)
{
product[i] = new Product();
}
//extra code
SOLUTION
I fixed the issue: instead of using .equals(), I tried using .equalsIgnoreCase() and it worked.
The method is returning as soon as it hits count 0 and it doesn't find a match. If you want to loop through your array until you find a matching name, your code should look like this:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
There are two ways to compare strings:
The first is to compare via addresses of the string. Such as: string blue = string red.
The second way to compare strings is through values. This can be done by using the string.equals("StringValue").
Since you have a return statement that will be reached on every posible situation (if condition is true or false), the method will always exit on the first iteration.
What can you do? If you want to return true if the name exists in the array and false otherwise, you can do:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName))
return true;
}
return false; // if after all elements has been checked
// and none was equal to 'checkName', return 'false'
}
How about collecting the names into a List (or Set) and check if checkName matches?
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName());
}
return productNames.contains(checkName);
}
Note that this will only work if you're comparing case-sensitive strings. Alternatively,
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName().toLowerCase());
}
return productNames.contains(checkName.toLowerCase());
}
If you do not like this approach, you can use the ones given already, and replace equals with equalsIgnoreCase.
This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 6 years ago.
ArrayList<String> values=new ArrayList<String>();
values.add("s");
values.add("n");
values.add("a");
values.add("s");
In this Array, I want to remove repeated values.
Try this...
ArrayList<String> values=new ArrayList<String>();
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(values);
values.clear();
values.addAll(hashSet);
Try below code,
ArrayList<String> values=new ArrayList<String>();
String newValue;
// repeated additions:
if (!values.contains(newValue)) {values.add(newValue);}
HashSet hs = new HashSet();
hs.addAll(demoArrayList); // demoArrayList= name of arrayList from which u want to remove duplicates
demoArrayList.clear();
demoArrayList.addAll(hs);
I think a real neat solution for enforcing unique array lists is this one, if it's not too much code for what you're trying to achieve.
public class UniqueOverridingList extends ArrayList {
public enum LAST_RESULT {
ADD, OVERRIDE, NOTHING;
}
private LAST_RESULT lastResult;
public boolean add(T obj) {
for (int i = 0; i < size(); i++) {
if (obj.equals(get(i))) {
set(i, obj);
lastResult = LAST_RESULT.OVERRIDE;
return true;
}
}
boolean b = super.add(obj);
if (b) {
lastResult = LAST_RESULT.ADD;
} else {
lastResult = LAST_RESULT.NOTHING;
}
return b;
}
public boolean addAll(Collection c) {
boolean result = true;
for (T t : c) {
if (!add(t)) {
result = false;
}
}
return result;
}
public LAST_RESULT getLastResult() {
return lastResult;
}
}
The class David Hedlund suggested can be made a lot shorter:
public class UniqueArrayList extends ArrayList {
/**
* Only add the object if there is not
* another copy of it in the list
*/
public boolean add(T obj) {
if(this.contains(obj))
return false;
return super.add(obj);
}
public boolean addAll(Collection c) {
boolean result = false;
for (T t : c) {
if (add(t)) {
result = true;
}
}
return result;
}
}
The addAll operation is modified too. The documentation states:
Returns: true if this list changed as a result of the call.
I modified the method to reflect this behaviour. There's still one problem. The documentation of the addAll() method also states:
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
The order might be broken by using this method. A possible workaround for this problem might be not supporting the addAll method.