Search code examples
javaclassarraylistcontain

How find if arraylist contains a value which is in class field?


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?

Solution

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

    2 Use method contains(Object o) from listx.