1

I have class:

static class AnotherClass {
        int number;
        String isPrime;

        public int getNumber() {
            return number;
        }

        public String getPrime() {
            return isPrime;
        }

        public void setNumber(int number) {
            this.number = number;
        }

        public void setPrime(String prime) {
            isPrime = prime;
        }

    }

and in main class i have:

    List<AnotherClass> listx = new ArrayList<AnotherClass>();//just a arraylist

for (int z = 0; z < howManyQuestions; z++) {//in loop i add class with fields
            AnotherClass classx = new AnotherClass();
            int valuex = Integer.parseInt(keyboardkey.readLine());

            classx.setNumber(valuex);//save value in this class

            String answer = Check(valuex);//i just get here string answer YES NO
            classx.setPrime(answer);

            listx.add(classx);//and i add this two fields of class to list

            System.out.println();

        }
INPUT: (i add value and check if it was input before)
3
4
3

OUTPUT
NO
NO
YES

How can i check if, for example value "3" is containing by list?
deadfish
  • 11,996
  • 12
  • 87
  • 136

4 Answers4

2

1 AnotherClass must implement equals() (and implement hashCode() accordingly).

2 Use method contains(Object o) from listx.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
2
private boolean contains(int i)
{
    for(int j: listx.getNumber()) { if(i == j) return true; }
    return false;
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

A Few notes -

your class doesn't require static. That has a use if you're declaring an inner class.

You have a container class holding a string that's dependant on an int, as well as the int. It'd be more idiomatic to have the check inside your class, e.g.

class AnotherClass {
        int number;


        public int getNumber() {
            return number;
        }

        public String getPrime() {
            return check(number)
        }

       private boolean check() { ... whatever logic you had .. }
}

If you're looking for "contains" functionality, you'd probably use a HashSet, or a LinkedHashSet( if you want to preserve the ordering ). If you want to do this with your created class you'll need to implement a hashCode() method to tell the hashSet how to know if it has a duplicate value.

Or you can just iterate over your list.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
1

You have to implement equals() for AnotherClass. The default equals() compares identity instead of value equality.

The javadoc for List.contains() says:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Op De Cirkel
  • 28,647
  • 6
  • 40
  • 53