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;
}
开发者_StackOverflow}
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?
1 AnotherClass must implement equals() (and implement hashCode() accordingly).
2 Use method contains(Object o) from listx.
private boolean contains(int i)
{
for(int j: listx.getNumber()) { if(i == j) return true; }
return false;
}
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.
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)).
加载中,请稍侯......
精彩评论