Videos
ArrayList has an indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
The indexOf() method does go through the entire list. Here's an excerpt from Java 7 source code:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
It'd be better to let Java go through it than write it yourself. Just make sure that your equals method is sufficient at finding the object you want. You'll also want to override hashCode() as well.
I won't write your equals method out, but I would recommend that you at least:
- Check for null
- Test if the instances you're comparing are the same
- You don't need to do
if(boolean_expr) { return true; }; just return the boolean expression. - Make sure you're actually overriding your
equalsmethod - the signature of that requires anObjectparameter, notDate.
The signature of your equals method is wrong. You are not overriding the equals in Object, but just overloading it.
To override the behavior of equals method in Object, your signature must exactly match with the one in Object. Try this:
public boolean equals(Object o) {
if(!(o instanceof Data)) return false;
Data other = (Data) o;
return (this.k == other.k && this.l == other.l);
}
In addition, as others suggested, it is a good idea to override hashCode method also for your object to work correctly in map based collections.
You're adding two String objects with the same value (empty string) to the list.
So your list looks like
["", ""]
You're then invoking the equivalent of indexOf(""), where indexOf(..) uses the Object#equals(Object) method to compare objects. The first element in the list is equal to "", so that index is returned.
Here you just create two objects and that has no value so it will be treated as empty string. So the Indexof will returns the first occurence of the given object.
If you assign different values to s and b then result what you are expecting that will get. Please try with below code.
String s = "String1";
myList.add(s);
String b = "String2";
myList.add(b);
int whereIsIt = myList.indexOf(s);
System.out.println(whereIsIt);
int whereIsIt2 = myList.indexOf(b);
System.out.println(whereIsIt2);
You cannot, in general, do any better than just looping through the list to find a value.
In terms of the code duplication, replace the body of customerExists with:
return customerPosition() >= 0;
And, in addTransaction(), store the result of customerPosition() in a variable, and use thatVariable >= 0 instead of calling customerExists().
If you are using Java 8+, you could use streams:
Optional<Customer> cust = customers.stream().filter(c -> c.getCustomerName().equals(customerName)).findFirst();
Then you don't have to worry about using the index at all.
Instead of using Multiple for loop, use single for loop and get the customer object and use that,
private Customer getCustomerUsingName(String customerName) {
for (int i = 0; i < customers.size(); i++) {
if(customers.get(i).getCustomerName().equalsIgnoreCase(customerName)) {
return customers.get(i);
}
}
return null;
}
Use the Customer in your method
public void addTransaction(String customerName, Double transactionValue) {
Customer customer = getCustomerUsingName(customerName)
if(customer == null) {
return;
}
customer.addTransaction(transactionValue);
}