So I have a database called appleList. Within it I have apple objects which within them has a list of items. I'm attempting to create a method where it returns true if item j is within the list of customer r and false if its not. This is what I have come up with so far...
public boolean (String m)
{
if(n[i] = p)
found = true;
return found;
}
Use equals() to compare Strings. Also, if n is an array you need to pass it in like below
public boolean hasProduct(String[] n, String p)
{
boolean found = false;
for(int i=0; i < n.size(); i++)
if(n[i].equals(p))
found = true;
return found;
}
There's an existing method in List that you can use
customerList.contains(object)
This method return true if the list contains the object
If you are using a custom object you can override the method equals, so the method above will use it to compare all objects in your list
public class MyCustomClass{
private Integer id;
//Other variables, getters and setters
#Override
public boolean equals(Object o2){
if(o2 instanceof MyCustomClass){
MyCustomClass o2custom = (MyCustomClass) o2;
if(o2custom.getId()!=null && this.id != null){
return o2custom.getId() == this.id;
}
}
return false;
}
}
Hugs
String n is not an array n[0] is wrong try this :
public boolean hasProduct(String p)
{
boolean found = false;
for(int i=0; i < customerList.size(); i++)
if(customerList.get(i) == p)
found = true;
return found;
}
To iterate an ArrayList you need to use .get(). Also, I added a break in your loop once the item is found.
public boolean hasProduct(String n, String p)
{
boolean found = false;
for(int i=0; i < this.customerList.size(); i++)
if(this.customerList.get(i) == p)
found = true;
break;
return found;
}
Since you're looking for a String in an ArrayList, you can simply do something like this:
public boolean hasProduct(ArrayList customerList, String p)
{
return customerList.contains(p);
}
As #DigaoParceiro mentions, if you're looking for a custom object within your collection, be sure to override equals() and hashCode(). String already provides this for you.
Related
According to this answer, roughly, if we had a Classroom object array of student objects, class[index] != student1. I believe this is the mistake I am making in implementing my equals method to compare the array[index] object to another object. I believed the array[index] and the object I am comparing against to be the same.
The code below shows my getNumStudents method in which I try to count the number of times a student id shows up in a class. ID represents brand shoes he or she likes (practice exercise out of lecture). This method is in my classroom object class which implements an interface.
#Override
public int getNumStudents(T anEntry) {
int count = 0;
for (int index = 0; index < numberOfEntries; index++) {
if (roster[index].equals(anEntry)) )
{
counter++;
}
}
return count;
}
My equals method is as such and is implemented in the student class:
public boolean equals(Student student) {
if (this == student)
{
return true;
}
if (student == null)
{
return false;
}
if (this.getID() != student.getID())
{
return false;
}
return true;
}
I don't know if I properly did the hashCode override but here it is (in Student class):
#Override
public int hashCode() {
int result = 17;
result = 31 * result + studentID;
return result;
}
I've narrowed down where the bug is to most likely here:
if (roster[index].equals(anEntry)) )
specifically
roster[index].equals(anEntry))
What should I call or how should I adjust my getNumStudents(T anEntry) method to properly return the number of students with a certain ID (representing a shoe type) within a Classroom object array?
Your equals signature is wrong.
The correct signature of equals method must be as follows.
public boolean equals(Object other)
Then inside the method you should check if it is of comparable type and if you really need it to be of type Student, you have to check for this and return false otherwise.
In your case that would be a minimal change required for your implementation:
public boolean equals(Object other)
{
if (this == other)
{
return true;
}
// This also works if `other` is `null`
if (!(other instanceof Student))
{
return false;
}
// Now we cast it to `Student`
final Student student = (Student) other;
if (this.getID() != student.getID())
{
return false;
}
return true;
}
I'm writing a method that returns a Set<String>. The set may contain 0, 1, or 2 objects. The string keys are also quite small (maximum 8 characters). The set is then used in a tight loop with many iterations calling contains().
For 0 objects, I would return Collections.emptySet().
For 1 object, I would return Collections.singleton().
For 2 objects (the maximum possible number), a HashSet seems overkill. Isn't there a better structure? Maybe a TreeSet is slightly better? Unfortunately, I'm still using Java 7 :-( so can't use modern things like Set.of().
An array of 2 strings would probably give the best performance, but that's not a Set. I want the code to be self-documenting, so I really want to return a Set as that is the logical interface required.
Just wrap an array with an AbstractSet. You only have to implement 2 methods, assuming you want an unmodifiable set:
class SSet extends AbstractSet<String> {
private final String[] strings;
SSet(String[] strings) {
this.strings = strings;
}
#Override
public Iterator<String> iterator() {
return Arrays.asList(strings).iterator();
}
#Override
public int size() {
return strings.length;
}
}
If you want, you can store the Arrays.asList(strings) in the field instead of a String[]. You can also provide 0, 1 and 2-arg constructors if you want to constrain the array only to be that length.
You can also override contains:
public boolean contains(Object obj) {
for (int i = 0; i < strings.length; ++i) {
if (Objects.equals(obj, strings[i])) return true;
}
return false;
}
If you don't want to create a list simply to create an iterator, you can trivially implement one as an inner class:
class ArrayIterator implements Iterator<String> {
int index;
public String next() {
// Check if index is in bounds, throw if not.
return strings[index++];
}
public boolean hasNext() {
return index < strings.length;
}
// implement remove() too, throws UnsupportedException().
}
The set is then used in a tight loop with many iterations calling contains().
I would probably streamline it for this. Perhaps something like:
public static class TwoSet<T> extends AbstractSet<T> {
T a = null;
T b = null;
#Override
public boolean contains(Object o) {
return o.equals(a) || o.equals(b);
}
#Override
public boolean add(T t) {
if(contains(t)){
return false;
}
if ( a == null ) {
a = t;
} else if ( b == null ) {
b = t;
} else {
throw new RuntimeException("Cannot have more than two items in this set.");
}
return true;
}
#Override
public boolean remove(Object o) {
if(o.equals(a)) {
a = null;
return true;
}
if(o.equals(b)) {
b = null;
return true;
}
return false;
}
#Override
public int size() {
return (a == null ? 0 : 1) + (b == null ? 0 : 1);
}
#Override
public Iterator<T> iterator() {
List<T> list;
if (a == null && b == null) {
list = Collections.emptyList();
} else {
if (a == null) {
list = Arrays.asList(b);
} else if (b == null) {
list = Arrays.asList(a);
} else {
list = Arrays.asList(a, b);
}
}
return list.iterator();
}
}
You can achieve this by
Make a class that implements Set interface
Override add and remove method
Add value upon class initialisation by super.add(E element)
Use that class instead
I'm trying to implement a containsAll method, but I don't understand why it's returning incorrect results. Please, help me.
public boolean contains(Object o) {
for (int ob = 0; ob < size; ob++) {
if (o == obj[ob])
return true;
}
return false;
}
public boolean containsAll(MyList c) {
for (int ob = 0; ob < size; ob++) {
c.toArray();
if (c.contains(obj[ob]))
{
return true;
}
}
return false;
}
It returns an incorrect result, because you return true after the first matching element is found. The logic should be along the lines of:
for (int ob = 0; ob < size; ob++) {
/* ... */
if (!c.contains(obj[ob])) {
return false;
}
}
return true;
I.e. return false after finding the first non-matching element, and only return true after checking all elements.
Also note that using ==, you're performing a strict identity comparison. If that's not what you're after, consider using equals() instead.
I fill up an Array List with some numbers and want to find a specific number that is in the Array List and get its position (the index) in my Array List.
Any example would be great!
for example
ProClon.indexOf(spro.getId(id));
First override equals() method with the specified field. then You can use indexOf.(object)
class A {
int i;
// other fields
public A(int i) {
this.i = i;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return i == a.i;
}
#Override
public int hashCode() {
return i;
}
}
List<A> list = new ArrayList<>();
list.indexOf(new A(3));
check the api of arrayList. indexOf(Object o); does exactly what you need.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
Just use method indexOf in array
arrayName.indexOf(object)
EDIT: With your help I managed to fix my problem. I have edited my code to now show how I had to have it set up to get it working.
Currently I am having trouble coding a part which compares the content of two iterators. As part of the requirements for my assignment, I need to use a linkedlist to store the individual characters of the entered String. I have gotten to the point where I have two iterators which would contain the input one way and the reverse way.
String palindrom = input.getText();
String [] chara = palindrom.split (""); //this is successfully splitting them, tested.
int length = palindrom.length( ); // length == 8
System.out.println (length); //can use this for how many checks to do?
LinkedList ll = new LinkedList(Arrays.asList(chara));
Iterator iterator = ll.iterator();
Iterator desIterator = ll.descendingIterator();
/*while(iterator.hasNext() ){
System.out.println(iterator.next() );
}
while(desIterator.hasNext() ){
System.out.println(desIterator.next() );
}*/
boolean same = true;
while(iterator.hasNext()){
if(!iterator.next().equals(desIterator.next())){
same = false;
break;
}
}
And using the System.out I can see that they are being stored correctly, but I don't know how to check if the iterators store the same contents. What would be one of the simplest methods to compare the two iterators or convert them into something I can compare? To clarify I want to verify they contain the same elements in the same order.
boolean same = true;
while(iterator.hasNext()){
if(!desIterator.hasNext() || !iterator.next().equals(desIterator.next())){
same = false;
break;
}
}
System.out.println(same);
You need to iterate over both iterators simultaneously, i.e. with one loop. Here is a general comparison function (0 when equal, < 0 when A < B, > 0 when A > B):
static <T extends Comparable<S>, S> int compare(Iterator<T> a, Iterator<S> b) {
while (a.hasNext() && b.hasNext()) {
int comparison = a.next().compareTo(b.next());
if (comparison != 0) {
return comparison;
}
}
if (a.hasNext())
return 1;
if (b.hasNext())
return -1;
return 0;
}
To just check if they are equal, this can be simplified:
static <T, S> boolean equals(Iterator<T> a, Iterator<S> b) {
while (a.hasNext() && b.hasNext()) {
if (!a.next().equals(b.next())) {
return false;
}
}
if (a.hasNext() || b.hasNext()) {
// one of the iterators has more elements than the other
return false;
}
return true;
}
Guava implements this as Iterators.elementsEqual.
In both answers throw NullPointerException, if iterator.next() == null. This method is more optimal.
public static boolean equals(Iterator i1, Iterator i2) {
if (i1 == i2) {
return true;
}
while (i1.hasNext()) {
if (!i2.hasNext()) {
return false;
}
if (!Objects.equals(i1.next(), i2.next())) {
return false;
}
}
if (i2.hasNext()) {
return false;
}
return true;
}